Switch expression behavior in Go - Time & Space Complexity
We want to understand how the time it takes to run a switch expression changes as the number of cases grows.
How does adding more cases affect the work the program does?
Analyze the time complexity of the following code snippet.
func checkValue(x int) string {
switch x {
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
default:
return "Other"
}
}
This function uses a switch to return a string based on the input number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch checks each case one by one until it finds a match.
- How many times: In the worst case, it checks all cases once.
As the number of cases grows, the program may check more cases before finding a match.
| Number of Cases (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 roughly in a straight line with the number of cases.
Time Complexity: O(n)
This means the time to find the matching case grows linearly with the number of cases.
[X] Wrong: "Switch statements always run in constant time no matter how many cases there are."
[OK] Correct: The switch checks cases one by one, so more cases mean more checks in the worst case.
Understanding how switch statements scale helps you explain code efficiency clearly and shows you think about how programs work under the hood.
"What if the switch used a map lookup instead of cases? How would the time complexity change?"