0
0
C Sharp (C#)programming~5 mins

Switch statement execution in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Switch statement execution
O(1)
Understanding Time Complexity

We want to understand how the time it takes to run a switch statement changes as we add more cases.

Specifically, how does the number of cases affect the work done when the switch runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int GetDayNumber(string day) {
    switch(day) {
        case "Monday": return 1;
        case "Tuesday": return 2;
        case "Wednesday": return 3;
        case "Thursday": return 4;
        case "Friday": return 5;
        case "Saturday": return 6;
        case "Sunday": return 7;
        default: return 0;
    }
}
    

This code returns a number for each day of the week using a switch statement.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Hash computation on the input string and lookup in an optimized table generated by the compiler.
  • How many times: Constant time, regardless of the number of cases.
How Execution Grows With Input

As the number of cases grows, the switch still performs a constant amount of work thanks to compiler optimizations like perfect hashing for strings.

Input Size (number of cases)Approx. Operations
7~1 hash + lookup
70~1 hash + lookup
700~1 hash + lookup

Pattern observation: The number of operations remains constant regardless of the number of cases.

Final Time Complexity

Time Complexity: O(1)

This means the time to find the matching case is constant, independent of the number of cases.

Common Mistake

[X] Wrong: "Switch statements check cases one by one, so time grows linearly with the number of cases, O(n)."

[OK] Correct: Modern C# compilers optimize switch statements on strings using hash tables or perfect hashes, enabling constant-time average case lookups.

Interview Connect

Understanding switch optimizations demonstrates knowledge of low-level compiler behavior and efficient data structures.

Self-Check

"What if this was implemented as a series of if-else if statements? How would the time complexity change?"