Performance (Part 1): From 6 min to 2 sec

by Oct 17, 2018

Here is a common mistake found in many PowerShell scripts:

$start = Get-Date

$bucket = @()

1..100000 | ForEach-Object {
    $bucket += "I am adding $_"
}

$bucket.Count

(Get-Date) - $start

In this design, scripts are using an empty array, then employ some sort of loop to add items to the array. When you run it, you’ll notice that it takes forever. In fact, it took more than 6 minutes on our test system and may take even longer on yours.

Here is what is causing the slowness: the operator “+=” is evil when applied to arrays, because even though it seems to dynamically extend the array, in reality it creates a new array with one more element each time you use “+=”.

To improve performance drastically, let PowerShell do the array creation: when you return things, PowerShell automatically creates an array for you – fast:

$start = Get-Date

$bucket = 1..10000 | ForEach-Object {
    "I am adding $_"
}

$bucket.Count

(Get-Date) - $start

The result is exactly the same, but instead of running for 6+ minutes, it only takes 46 seconds on PowerShell 5.1 and a mere 1.46 seconds on PowerShell 6.1. Tomorrow, we’ll try and improve performance with another trick even more.

Twitter This Tip! ReTweet this Tip!