Default parameter values in PowerShell - Time & Space Complexity
We want to understand how using default values for parameters affects how long a script takes to run.
Specifically, does setting default values change the work done as input grows?
Analyze the time complexity of the following code snippet.
function Get-Sum {
param(
[int[]]$Numbers = @(1, 2, 3, 4, 5)
)
$sum = 0
foreach ($num in $Numbers) {
$sum += $num
}
return $sum
}
This function sums numbers in an array. If no array is given, it uses a default list of five numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for each number in the input array.
The time to run grows as the number of numbers grows, because the loop adds each one.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 (default) | 5 additions |
| 10 | 10 additions |
| 100 | 100 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of numbers to add.
[X] Wrong: "Using default values makes the function run faster or slower depending on input size."
[OK] Correct: The default value is just a fixed small list. The time depends on how many numbers are actually processed, not on whether they came from default or input.
Understanding how default parameters affect performance helps you write clear and efficient scripts, a skill valued in real projects and interviews.
"What if the default parameter was a very large array instead of a small one? How would the time complexity change?"