Faster Array Manipulations

by Mar 16, 2016

The "+=" operator is pretty convenient and can add new elements to an array. If you need this more than once, for example in a loop, then this approach is extremely slow, though. Here is a comparison that also shows how you can speed up array manipulation considerably:

$ar = @()

# SLOW
Measure-Command {
  for ($x = 1 $x -lt 10000 $x += 1) 
  {
    $ar += $x
  }
}


# FAST
[System.Collections.ArrayList]$ar = @()
Measure-Command {
  for ($x = 1 $x -lt 10000 $x += 1) 
  {
    $null = $ar.Add($x)
  }
}

Twitter This Tip! ReTweet this Tip!