You can repeat arrays the same way you can do with strings:
$myArray = ,2 * $length
This means "Take an array with a single element 2 and repeat it $length times, getting a new array."
Note that you cannot use this to create multidimensional arrays, because the following:
$some2darray = ,(,2 * 1000) * 1000
It will simply create 1000 references to the internal array, which makes them useless for manipulation. In this case, you can use a hybrid strategy. I used
$some2darray = 1..1000 | ForEach-Object { ,(,2 * 1000) }
in the past but below performance measurements show that
$some2darray = foreach ($i in 1..1000) { ,(,2 * 1000) }
will be much faster.
Some performance measurements:
Command Average Time (ms) ------- ----------------- $a = ,2 * $length 0,135902
Taken by running each option 50 times through the Measure-Command , each with the same value for $length and averaging the results.
Positions 3 and 4 are actually a bit of a surprise. This seems to be much better than range foreach instead of the usual for loop.
The code to create the chart above is:
$length = 16384 $tests = '$a = ,2 * $length', '[int[]]$a = [System.Linq.Enumerable]::Repeat(2, $length)', '$a = for ($i = 0; $i -lt $length; $i++) { 2 }', '$a = foreach ($i in 1..$length) { 2 }', '$a = 1..$length | %{ 2 }', '$a = @(); for ($i = 0; $i -lt $length; $i++) { $a += 2 }', '[int[]]$a = -split "2 " * $length' $tests | ForEach-Object { $cmd = $_ $timings = 1..50 | ForEach-Object { Remove-Variable i,a -ErrorAction Ignore [GC]::Collect() Measure-Command { Invoke-Expression $cmd } } [pscustomobject]@{ Command = $cmd 'Average Time (ms)' = ($timings | Measure-Object -Average TotalMilliseconds).Average } } | Sort-Object Ave* | Format-Table -AutoSize -Wrap