Array – it is faster for PowerShell ArrayList Add or = operator?

I found that if you create an array in the power shell and do this:

$myArray = @()
$myArray += 7

Each time this statement is executed, it will create a new array containing 7 at the end, return the new array and delete the old array! Basically, we do this in a loop of 10000 iterations, making it very slow!

If I use ArrayList, by calling Add (x), we find it 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 format of = X We hope we don't have to change all the code to Add (x) format

Solution

Use the following command to obtain these results, 10000 iterations

. Add() took 0s 45.2869ms

=It took 2S 900.2777 milliseconds

Measure-Command -Expression {
    $i = 0
    $myArrayList = New-Object System.Collections.ArrayList
    Do {
        #$myArrayList.add($i)
        $myArrayList += $i
        $i++
    } While ($i -lt 10000)
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>