Why pattern matching matters in C Sharp (C#) - Performance Analysis
When using pattern matching in C#, it is important to understand how it affects the speed of your program.
We want to know how the time to check patterns grows as we add more cases or more complex patterns.
Analyze the time complexity of this pattern matching example.
string Describe(object obj) {
return obj switch {
int i => $"Integer {i}",
string s => $"String {s}",
null => "Null value",
_ => "Unknown type"
};
}
This code checks the type of an object and returns a description based on the pattern matched.
Look at what repeats when matching patterns.
- Primary operation: Checking each pattern case one by one.
- How many times: Up to the number of patterns until one matches.
As you add more pattern cases, the program may check more before finding a match.
| Number of Patterns (n) | Approx. Checks |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows linearly with the number of patterns.
Time Complexity: O(n)
This means the time to find a matching pattern grows in direct proportion to how many patterns you have.
[X] Wrong: "Pattern matching always runs in constant time because it looks simple."
[OK] Correct: Each pattern is checked one after another until a match is found, so more patterns mean more checks.
Understanding how pattern matching scales helps you write efficient code and explain your choices clearly in interviews.
What if we used a dictionary lookup instead of switch pattern matching? How would the time complexity change?