If-elseif-else statements in PowerShell - Time & Space Complexity
We want to understand how the time it takes to run if-elseif-else statements changes as the input changes.
Specifically, we ask: How does the number of checks grow when we add more conditions?
Analyze the time complexity of the following code snippet.
param($value)
if ($value -eq 1) {
Write-Output "One"
} elseif ($value -eq 2) {
Write-Output "Two"
} else {
Write-Output "Other"
}
This code checks a value and prints a message depending on which condition matches first.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions one by one.
- How many times: At most, it checks each condition once until one matches.
As the number of conditions grows, the checks increase one by one until a match is found or all are checked.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 conditions | Up to 2 checks |
| 10 conditions | Up to 10 checks |
| 100 conditions | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of conditions.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of conditions to check.
[X] Wrong: "If-elseif-else runs all conditions every time."
[OK] Correct: The code stops checking as soon as one condition is true, so it does not always check all conditions.
Understanding how if-elseif-else statements scale helps you write efficient scripts and explain your code clearly in real situations.
"What if we replaced if-elseif-else with separate if statements? How would the time complexity change?"