Switch statement execution in PHP - Time & Space Complexity
We want to understand how long a switch statement takes to run as the number of cases grows.
How does the time to find the matching case change when there are more options?
Analyze the time complexity of the following code snippet.
function getDayName(int $dayNumber): string {
switch ($dayNumber) {
case 1: return 'Monday';
case 2: return 'Tuesday';
case 3: return 'Wednesday';
case 4: return 'Thursday';
case 5: return 'Friday';
case 6: return 'Saturday';
case 7: return 'Sunday';
default: return 'Invalid day';
}
}
This code returns the name of the day based on a number using a switch statement.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct jump to the matching case via a jump table or hash lookup (compiler-optimized).
- How many times: Constant time, typically 1 operation regardless of cases.
As the number of cases increases, the time remains constant due to optimization.
| Input Size (number of cases) | Approx. Operations |
|---|---|
| 10 | ~1 jump |
| 100 | ~1 jump |
| 1000 | ~1 jump |
Pattern observation: Time stays constant; compiler uses jump tables for dense integers.
Time Complexity: O(1)
This means the time to find the matching case is constant, independent of the number of cases.
[X] Wrong: "Switch statements check cases one by one, so O(n)."
[OK] Correct: Compilers optimize switches on integers to jump tables or binary search/hashes, making it O(1) average/worst case for typical use.
Understanding switch optimizations shows deep knowledge of low-level compiler behavior and why simple structures can be efficient at scale.
"What if the switch used strings or sparse values? How might complexity change?"