0
0
PowerShellscripting~5 mins

Custom objects (PSCustomObject) in PowerShell - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom objects (PSCustomObject)
O(n^2)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As you increase n, the number of objects created and added grows directly with n.

Input Size (n)Approx. Total Operations
1055 (10 creations + 45 copies)
1005,050 (100 creations + 4,950 copies)
1000500,500 (1,000 creations + 499,500 copies)

Pattern observation: The work grows quadratically as n grows; doubling n roughly quadruples the work.

Final Time Complexity

Time Complexity: O(n^2)

This means the time to create and add objects grows quadratically with the number of objects.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if we used a list object instead of an array and added items with Add()? How would the time complexity change?