Loops and Arrays (and some surprises)

by May 13, 2016

Frequently, loops are used to retrieve (or generate) data, then save it to a variable. There can be tremendous performance differences though. To generate 10.000 random numbers, for example, you might look into something like this:

$numbers = @()

for ($x = 1 $x -le 10000 $x++) 
{
  $numbers += Get-Random -Minimum 1 -Maximum 7
}

$numbers.Count

It takes many seconds, and becomes almost paralyzing with even larger loop iterations.

Here is a similar approach that is many times faster:

Here is a similar approach that is many times faster:
$numbers = for ($x = 1 $x -le 10000 $x++) 
{
  Get-Random -Minimum 1 -Maximum 7
}

$numbers.Count

Instead of saving the results to a variable with each iteration, leave it to PowerShell to create and maintain the array. Just save the results of the loop when it is done.

Twitter This Tip! ReTweet this Tip!