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

2 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.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s