Speeding Up Arrays

by Jun 23, 2014

When you assign new items to an array often, you may experience a performance problem. Here is a sample that illustrates how you should not do it:

Measure-Command {
  $ar = @()

  for ($x=0 $x -lt 10000 $x++)
  {
    $ar += $x  
  }
}

In a loop, an array receives a lot of new items using the operator "+=". This takes a long time, because PowerShell needs to create a new array each time you change its size.

Here is an approach that is many, many times faster–using an ArrayList which is optimized for size changes:

Measure-Command {
  $ar = New-Object -TypeName System.Collections.ArrayList

  for ($x=0 $x -lt 10000 $x++)
  {
    $ar.Add($x)
  }
}

Both pieces of code achieve the same thing. The second approach is a lot faster.

Twitter This Tip! ReTweet this Tip!