I found that if you create an array in PowerShell and do this:
$myArray = @()
$myArray += 7
Everytime you execute this statement it creates a NEW array with 7 at the end, and returns the new array and deletes the old array! Basically, we were doing this in a loop of like 10,000 iterations, makes it very slow!
If I use an ArrayList instead, via calling .Add(x)
, we found it was WAY faster. My question is which code is faster?
$myArrayList.Add(x)
or
$myArrayList += x
Or are they the same? Because our existing code is in the += x
format. We hope not to have to change all of the code to the .Add(x)
format.
Got these results with the below command, 10,000 iterations.
.add()
took 0s 45.2869ms
+=
took 2s 900.2777 ms
Measure-Command -Expression {
$i = 0
$myArrayList = New-Object System.Collections.ArrayList
Do {
#$myArrayList.add($i)
$myArrayList += $i
$i++
} While ($i -lt 10000)
}
Drew's answer shows pretty well that +=
with arrays in PowerShell is not performant; you already found the reason in your question (a new array is created every time, all elements copied, etc.).
Do note that ArrayList is not your only alternative. Sometimes just changing the way you do things will make a big difference; for example loops and iterations are common in PowerShell and making an array of the output by assignment is very fast, and also better syntax in my opinion.
Compare this (2s 406ms
):
Measure-Command -Expression {
$a = @()
1..10000 | % { $a += $_*2 }
}
to this (60ms
):
Measure-Command -Expression {
$a = 1..10000 | % { $_*2 }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With