Custom objects (PSCustomObject) in PowerShell - Time & Space Complexity
When creating custom objects in PowerShell, it is helpful to understand how the time to build these objects grows as you add more data.
We want to know how the work changes when making many custom objects.
Analyze the time complexity of the following code snippet.
$results = @()
for ($i = 1; $i -le $n; $i++) {
$obj = [PSCustomObject]@{
Id = $i
Name = "Item$i"
}
$results += $obj
}
$results
This code creates $n custom objects, each with two properties, and adds them to an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new custom object (O(1)) and adding it to the array with += (O(current size)).
- How many times: n times, but total cost is O(n2).
As you increase n, the number of objects created and added grows directly with n.
| Input Size (n) | Approx. Total Operations |
|---|---|
| 10 | 55 (10 creations + 45 copies) |
| 100 | 5,050 (100 creations + 4,950 copies) |
| 1000 | 500,500 (1,000 creations + 499,500 copies) |
Pattern observation: The work grows quadratically as n grows; doubling n roughly quadruples the work.
Time Complexity: O(n^2)
This means the time to create and add objects grows quadratically with the number of objects.
[X] Wrong: "Adding objects to the array is always fast and constant time."
[OK] Correct: In PowerShell, adding to an array with += creates a new array each time, so the time grows more than expected as the array gets bigger.
Understanding how loops and object creation scale helps you write scripts that stay fast even with lots of data. This skill shows you can think about efficiency in real tasks.
What if we used a list object instead of an array and added items with Add()? How would the time complexity change?