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.