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

Switch expression (modern C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Switch expression (modern C#)
O(1)
Understanding Time Complexity

We want to understand how the time it takes to run a switch expression changes as the input grows.

Specifically, does adding more cases make the program slower?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


string GetDayType(int day) => day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 => "Saturday",
    7 => "Sunday",
    _ => "Invalid"
};
    

This code returns the name of the day based on a number using a modern switch expression.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: None repeating. The switch is a single control structure.
  • How many times: Evaluated once per call in constant time.
How Execution Grows With Input

The C# compiler optimizes switch expressions on integers to a jump table (array lookup), which is constant time regardless of the number of cases.

Input Size (number of cases)Approx. Operations
51 lookup
101 lookup
1001 lookup

Pattern observation: Constant time O(1), independent of the number of cases.

Final Time Complexity

Time Complexity: O(1)

This means the execution time is constant, even as the number of cases grows, thanks to compiler optimizations like jump tables.

Common Mistake

[X] Wrong: "Switch expressions check cases one by one, so O(n) where n is number of cases."

[OK] Correct: For integral types like int with known values, the compiler generates a jump table for O(1) lookup, not linear scanning.

Interview Connect

Understanding compiler optimizations for switch shows deep knowledge of how high-level code translates to efficient machine instructions.

Self-Check

"What if the switch expression used a dictionary lookup instead? How would the time complexity change?"

(Hint: Dictionary lookup is amortized O(1), similar to switch jump table.)