PowerShell – Array vs. ArrayList Performance

Let’s take a look at performance when dealing with looping over an array variable; adding a new item and overall performance.
A standard array object in PowerShell is of a fixed size when created and cannot expand automatically. When you use the “+=” operator to append an entry, a new array object is created in memory with the additional overall previous array object. This leads to a large performance hit when dealing with a large number of items and increased memory consumption. For example:


$ArrayList = New-Object -TypeName 'System.Collections.ArrayList';
$Array = @();


Measure-Command
{
for($i = 0; $i -lt 10000; $i++)
{
$null = $ArrayList.Add("Adding item $i")
}
};
Measure-Command
{
for($i = 0; $i -lt 10000; $i++)
{
$Array += "Adding item $i"
}
};

Recommendation: use generics!

Advertisements

4 responses to “PowerShell – Array vs. ArrayList Performance

  1. Nice example.

    Interestingly, piping $ArrayList.Add() to Out-Null seems to slow this test down significantly (although still about 5x faster on my machine than += with a fixed array). Using [void]$ArrayList.Add(“Adding item $i”) instead was about 70x faster than a fixed array.

  2. Oh my god, thanks for this. Very concise and saved my day.
    I was writing a PowerShell script for work to split up about 250,000 account numbers into different files. After the script ran for like 45 minutes and still didn’t finish, I felt very discouraged thinking that this script might just not work out. After seeing your explanation, I realize how horrifically inefficient “+=” would be with so many records and how this scales badly exponentially as the records increase.
    After altering my code to your suggestion? Took 37 seconds.
    Phew! Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s