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 – Check For Matching Items In Seperate Arrays

$test1 = (1,2,3)
$test2 = (2,4,6)
$test3 = (1,3,5)
( ( $test1 + $test2 + $test3) | Group-Object |?{$_.Count -gt 1}).Values

Example outputs:

PS C:\> $test1 = (1,2,3)
$test2 = (2,4,6)
$test3 = (1,3,5)
( ( $test1 + $test2 + $test3) | Group-Object |?{$_.Count -gt 1}).Values
1
2
3
PS C:\>  

PowerShell Special Characters and Tokens (short-handing):
http://www.neolisk.com/techblog/powershell-specialcharactersandtokens