Enum with switch pattern in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run code with an enum and switch pattern changes as the number of enum cases grows.
Specifically, how does checking each enum value with a switch affect performance?
Analyze the time complexity of the following code snippet.
enum Color { Red, Green, Blue, Yellow }
string GetColorMessage(Color color)
{
return color switch
{
Color.Red => "Stop",
Color.Green => "Go",
Color.Blue => "Calm",
Color.Yellow => "Caution",
_ => "Unknown"
};
}
This code returns a message based on the color enum using a switch expression.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch checks the enum value once to find the matching case.
- How many times: Exactly one check per call; no loops or repeated traversals.
Since the switch checks only once per call, the time does not grow with the number of enum values in a simple way.
| Input Size (number of enum cases) | Approx. Operations per call |
|---|---|
| 4 | 1 check |
| 10 | 1 check |
| 100 | 1 check |
Pattern observation: The operation count stays about the same for each call, regardless of enum size.
Time Complexity: O(1)
This means the time to get the message stays constant no matter how many enum values exist.
[X] Wrong: "More enum cases always make the switch slower because it checks each case one by one."
[OK] Correct: The compiler often optimizes switch statements on enums to jump directly to the matching case, so it does not check all cases one by one.
Understanding how switch statements work with enums helps you explain code efficiency clearly and shows you know how language features affect performance.
"What if we replaced the switch with a loop that checks each enum case one by one? How would the time complexity change?"