Pattern matching in switch in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run a switch statement with pattern matching changes as the input changes.
Specifically, how does the number of checks grow when we add more patterns?
Analyze the time complexity of the following code snippet.
object obj = GetInput();
switch (obj)
{
case int i:
Console.WriteLine($"Integer: {i}");
break;
case string s when s.Length > 5:
Console.WriteLine($"Long string: {s}");
break;
case null:
Console.WriteLine("Null value");
break;
default:
Console.WriteLine("Other type");
break;
}
This code checks the input against several patterns to decide what to print.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement checks each pattern one by one until it finds a match.
- How many times: At most, it checks all patterns once each in order.
Each new pattern adds one more check to do in the worst case.
| Input Size (number of patterns) | Approx. Operations (pattern checks) |
|---|---|
| 4 | Up to 4 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of patterns.
Time Complexity: O(n)
This means the time to find a matching pattern grows linearly with the number of patterns to check.
[X] Wrong: "The switch with pattern matching checks all patterns instantly or in constant time."
[OK] Correct: The switch checks patterns one after another until it finds a match, so more patterns mean more checks.
Understanding how pattern matching scales helps you explain code efficiency clearly and shows you know how language features work under the hood.
What if the switch used a hash-based lookup for patterns? How would the time complexity change?