Why control flow directs execution in PowerShell - Performance Analysis
Control flow guides which parts of a script run and when. Analyzing time complexity helps us see how this guidance affects the total work done.
We want to know how the script's running time changes as input size grows, based on its control flow.
Analyze the time complexity of the following code snippet.
$count = 0
for ($i = 0; $i -lt $n; $i++) {
if ($i % 2 -eq 0) {
$count += 1
}
}
Write-Output $count
This script counts how many even numbers are in a range from 0 to n-1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs through each number from 0 to n-1.
- How many times: It repeats exactly n times, checking each number once.
As n grows, the loop runs more times, doing one check per number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the script's running time grows in a straight line with the input size.
[X] Wrong: "Because the if condition skips some numbers, the loop runs fewer times and is faster than O(n)."
[OK] Correct: The loop still runs n times; the condition only decides what happens inside, so the total steps still grow with n.
Understanding how control flow affects execution helps you explain script efficiency clearly. This skill shows you can think about how code behaves as inputs change.
"What if we added a nested loop inside the if condition that also runs up to n times? How would the time complexity change?"