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

PowerShell – Single Quote vs. Double Quote

What’s the difference with quotes?

Single quote: It is taken literally and provided back.
Double quotes: PowerShell looks for the $ character inside of the double quotes. Once found, it assumes the following characters are the name of a variable up to the first space, is a variable name.

Sample:

[System.String]$a = 'Hello'
$b = '$a World!'
# $b prints: $a World!
$c = "$a World!"
# $c prints: Hello World!