你可以重复数组,就像你可以对字符串做的那样:
$myArray = ,2 * $length
这意味着 »获取具有单个元素 2 的数组并重复 $length 次,生成一个新数组。«。
请注意,您不能真正使用它来创建多维数组,原因如下:
$some2darray = ,(,2 * 1000) * 1000
只会创建对内部数组的 1000 个引用,使它们无法用于操作。在这种情况下,您可以使用混合策略。我用过
$some2darray = 1..1000 | ForEach-Object { ,(,2 * 1000) }
过去,但以下性能测量表明
$some2darray = foreach ($i in 1..1000) { ,(,2 * 1000) }
会是一个更快的方法。
一些性能测量:
Command Average Time (ms)
------- -----------------
$a = ,2 * $length 0,135902 # my own
[int[]]$a = [System.Linq.Enumerable]::Repeat(2, $length) 7,15362 # JPBlanc
$a = foreach ($i in 1..$length) { 2 } 14,54417
[int[]]$a = -split "2 " * $length 24,867394
$a = for ($i = 0; $i -lt $length; $i++) { 2 } 45,771122 # Ansgar
$a = 1..$length | %{ 2 } 431,70304 # JPBlanc
$a = @(); for ($i = 0; $i -lt $length; $i++) { $a += 2 } 10425,79214 # original code
通过对Measure-Command 运行每个变体 50 次,每个变体具有相同的 $length 值,然后对结果取平均值。
实际上,位置 3 和 4 有点出人意料。显然,在一定范围内使用foreach 比使用普通的for 循环要好得多。
生成上图的代码:
$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