Powershell makes it easy and convenient to add stuff into an array. This works well and is easy to write:
$SomeVariable = 'Here is some text'
$SomeVariable += 'And some more'
There is a catch however. When you do this, Powershell creates an array. And Powershell arrays are static. What if your array becomes big ? It can happen if you have some form of repetitive processing… Well… If your variables has 100 entries, and you add one, Powershell will basically :
- Copy the 100-element array into a new 101-element array
- Delete the old 100-element array
The result: Your code is running exponentially slower.
Because Powershell is based on .Net, an easy solution is, instead, to create an ArrayList. ArrayLists are dynamic structures, so adding elements to them is much faster. It would be something like this:
$SomeVariable = [System.Collections.ArrayList]@()
[void]$SomeVariable.Add('Here is some text')
[void]$SomeVariable.Add('And some more')
MUCH faster! I had a script that went down from 12 minutes to 22 seconds thanks to this simple change.
As a side note, the Add method will return the index of the added element. This is why I wanted to use [void], because otherwise, this index will get added to the Powershell pipeline. This is something you may want, but more often than not, it will just ruin your pipeline. So be careful with that !
