Switch statement in PowerShell - Time & Space Complexity
We want to understand how the time it takes to run a switch statement changes as we add more cases.
Specifically, how does the number of cases affect the work done when matching a value?
Analyze the time complexity of the following code snippet.
$value = 3
switch ($value) {
1 { "One" }
2 { "Two" }
3 { "Three" }
4 { "Four" }
default { "Other" }
}
This code checks the value and runs the matching block among several cases.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each case one by one until a match is found.
- How many times: Up to the number of cases in the switch statement.
As the number of cases grows, the time to find a match grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The work grows directly with the number of cases.
Time Complexity: O(n)
This means the time to find a matching case grows linearly as you add more cases.
[X] Wrong: "The switch statement always runs in constant time no matter how many cases there are."
[OK] Correct: The switch checks cases one by one until it finds a match, so more cases mean more checks and more time.
Understanding how switch statements scale helps you write efficient scripts and explain your choices clearly in interviews.
"What if the switch statement used a hash table internally to jump directly to the matching case? How would the time complexity change?"