Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For PowerShell ArrayList, which is Faster .Add or += Operator?

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.

like image 716
Erik343 Avatar asked Oct 13 '25 05:10

Erik343


2 Answers

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)
}
like image 82
Drew Avatar answered Oct 15 '25 23:10

Drew


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 }
}
like image 36
briantist Avatar answered Oct 15 '25 23:10

briantist