且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何有效地填充数组在PowerShell中

更新时间:2023-11-11 09:54:40

您可以重复阵列,就像你可以用字符串做的:

You can repeat arrays, just as you can do with strings:

$myArray = ,2 * $length

这意味着»开始跟单元素数组 2 和重复 $长度次,产生了新的数组«。

This means »Take the array with the single element 2 and repeat it $length times, yielding a new array.«.

请注意,你不能真正使用它来创建多维数组,因为以下内容:

Note that you cannot really use this to create multidimensional arrays because the following:

$some2darray = ,(,2 * 1000) * 1000

只是创建1000个引用内阵列,使他们无用的操作。在这种情况下,你可以使用一个混合策略。我用

will just create 1000 references to the inner array, making them useless for manipulation. In that case you can use a hybrid strategy. I have used

$some2darray = 1..1000 | ForEach-Object { ,(,2 * 1000) }

在过去,但下面的性能的测量表明,

in the past, but below performance measurements suggest that

$some2darray = foreach ($i in 1..1000) { ,(,2 * 1000) }

将是一个更快的方法。

would be a much faster way.

某些性能测量:

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

测量命令摘自运行的每个变种50次,每次与 $长度相同的值,和平均结果。

Taken by running each variant 50 times through Measure-Command, each with the same value for $length, and averaging the results.

位置3和4是一个有点意外的,其实。显然,这是在一定范围内,以的foreach 高得多,而不是使用普通的循环。

Position 3 and 4 are a bit of a surprise, actually. Apparently it's much better to foreach over a range instead of using a normal for loop.

code生成如上图:

Code to generate above chart:

$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