Sometimes you need to add elements to an array in PowerShell within a loop without knowing beforehand how many elements you are going to add.
In the most cases using the += operator make it all work easily.
Since the += operator actually…
- …creates a new array in the memory with a length of the current array +1
- copies all the elements of the current array into the new array
- adds the new element at the end of the new array
- deletes the current array from memory…
…the whole process is extremely time consuming (or expensive) if your array grows larger and larger.
On the other hand, using the .Add() function at a System.Collections.ArrayList just adds a new element at the end of the array without copying it first, which is much faster.
Therefore, I would suggest using the .NET System.Collections.ArrayList instead as shown below.
To demonstrate the massive difference in performance between the += operator and the System.Collections.ArrayList, I wrote two short scripts to demonstrates the effect.
Using the += operator to fill an array
1 2 3 4 5 6 7 | Measure-Command { $myArrayList = @() for($i = 1; $i -le 100000; $i++){ $myArrayList += "another array element" } } |
As you can see, filling the array with 100’000 elements took a bit over 3 minutes.
1 2 3 4 5 6 7 8 9 10 11 | Days : 0 Hours : 0 Minutes : 3 Seconds : 12 Milliseconds : 236 Ticks : 1922365557 TotalDays : 0.00222496013541667 TotalHours : 0.05339904325 TotalMinutes : 3.203942595 TotalSeconds : 192.2365557 TotalMilliseconds : 192236.5557 |
Using the .NET System.Collections.ArrayList to fill an array
1 2 3 4 5 6 7 | Measure-Command { $myArrayList = New-Object System.Collections.ArrayList for($i = 1; $i -le 100000; $i++){ $myArrayList.add("another array element") } } |
Filling the array with 100’000 elements using the System.Collections.ArrayList only took 148 milliseconds and was therefore staggering 1’295.8 times faster!
1 2 3 4 5 6 7 8 9 10 11 | Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 148 Ticks : 1483534 TotalDays : 1.71705324074074E-06 TotalHours : 4.12092777777778E-05 TotalMinutes : 0.00247255666666667 TotalSeconds : 0.1483534 TotalMilliseconds : 148.3534 |
The difference will grow even bigger as the array gets bigger.