Why avoid += in Powershell?

First of all I want to confess that I was using += almost every time. I get acquainted with this technic back in college when I was learning C++ in around 2010. Since then I was using it all over the place. I was using it heavily in C++, C# and since 2013 in Powershell… Until 2017.

One day I was listening to Poweshell Scripting podcast and hosts said that there was PS  conference   in Europe with bunch of interesting sessions. I was very excited and want to check it ASAP. The most thrilling was that all of the sessions were recorded and are available on YouTube in very good quality.

Right after the podcast I found PowerShell Conference EU Channel and started to watch all talks. The opening talk was performed by Tobias Weltner (@TobiasPSP) – Powershell MVP and organizer of that conference. He was discussing different tricks in Powershell and of course he was talking/proving why += is so bad habit. 

He explains how += works: it treats static array as dynamic one and basically creates new array, copy the items from previous one and only after that add new items. This  is very,very slow.

Here are few examples and time needed to perform those operations:

If we just increase number of element 10 times its gonna take around 225.5 times slower:

Then Tobias provides awesome workaround – use .Net as “smart ass” .NET developers created array list which is much more faster:

Then Tobias provides awesome workaround – use .Net as “smart ass” .NET developers created array list which is much more faster:

[System.Collections.ArrayList]$MyArrayList=New-Object "System.Collections.ArrayList" 
1..10000 | ForEach-Object {$MyArrayList.Add($_) | Out-null}

As you can see using ArrayList appears to be 6.5 times faster than += and  if we increase number of elements 10 times it gonna take few seconds not minutes :

[System.Collections.ArrayList]$MyAnotherList= New-Object "System.Collections.ArrayList" 1..100000 | ForEach-Object {$MyAnotherList.Add($_) | Out-null}

At the end Tobias reveals an incredible life hack:

Powershell is a .NET based language and if you do not remember or to lazy to memorize the array list type (System.Collections.ArrayList>) just let Powershell do it for you:

$MyArray=1..10000 | ForEach-Object {$_}

This is the most Powershellish way to do it.

Tobias’s  full talk can be found here.

That day completely changed all my future scripts(and bunch of existing one) and substitute += to ArrayList.Add().

Thanks a lot for reading.

If you have any questions please leave them in a comment section below.

One thought on “Why avoid += in Powershell?”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.