ForEach loop in PowerShell - Time & Space Complexity
When using a ForEach loop in PowerShell, it is important to understand how the time it takes to run grows as the list gets bigger.
We want to know how the number of steps changes when the input list grows.
Analyze the time complexity of the following code snippet.
$numbers = 1..100
foreach ($num in $numbers) {
Write-Output $num
}
This code prints each number from a list of numbers one by one.
- Primary operation: The loop runs once for each item in the list.
- How many times: Exactly as many times as there are items in the list.
As the list gets bigger, the number of steps grows in a straight line with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: Doubling the list size doubles the work done.
Time Complexity: O(n)
This means the time to finish grows directly in proportion to the number of items.
[X] Wrong: "The loop runs in constant time no matter how big the list is."
[OK] Correct: Each item must be handled once, so more items mean more steps.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how to write efficient scripts.
"What if we nested one ForEach loop inside another over the same list? How would the time complexity change?"