来补充FoxDeploy 的有用答案 https://stackoverflow.com/a/38313607/45375以更广阔的视野管道使用:
tl;dr:
一般来说管道是 PowerShell 不可或缺的一个强大概念,尽管它们引入了处理开销,但因其概念优雅而值得使用,除非它们出现性能问题。
为了让您了解相对性能,以下是比较解决方案的测试时间,由输入集合的大小和平均运行次数参数化。
在底部找到测试脚本。
请注意,输入数据的构造是为了将第一个(也是唯一一个)不存在的路径放置在middle输入集合的。
这种选择极大地影响了性能Select-Object -First 1
解决方案:
如果您在开始,如果你放置它,它会表现最好放在最后或根本不包含,就不会再有任何表现(反之)。
我的机器(2012 年末的 iMac)中的样本数字,以秒为单位:
> .\Test.ps1 -count 10 -repeat 10 # 10 input items, timing averaged over 10 runs
Command 10-run average
------- --------------
-contains, no pipeline .00124
-contains, pipeline .00170
pipeline, where-object, select -first 1 .00276
pipeline, where-object .00314
pipeline, where-object, Test-Path in script block .00460
> .\Test.ps1 -count 100 -repeat 10
Command 10-run average
------- --------------
-contains, no pipeline .01190
pipeline, where-object, select -first 1 .01328
-contains, pipeline .01836
pipeline, where-object .02365
pipeline, where-object, Test-Path in script block .03725
> .\Test.ps1 -count 1000 -repeat 10
Command 10-run average
------- --------------
pipeline, where-object, select -first 1 .11154
-contains, no pipeline .11764
-contains, pipeline .16508
pipeline, where-object .22246
pipeline, where-object, Test-Path in script block .37015
> .\Test.ps1 -count 10000 -repeat 10
Command 10-run average
------- --------------
pipeline, where-object, select -first 1 1.09919
-contains, no pipeline 1.15089
-contains, pipeline 1.75926
pipeline, where-object 2.21868
pipeline, where-object, Test-Path in script block 3.65946
Test.ps1
param(
[int] $count = 50
,
[int] $repeat = 10
)
# Create sample input array.
$paths = @('c:') * $count
$paths[$paths.Count / 2] = 'nosuch'
$timingPropName = "$repeat-run average"
@(
[pscustomobject] @{ Command = "-contains, no pipeline"; $timingPropName =
(1..$($repeat) | % { (Measure-Command { (Test-Path $paths) -contains $false }).TotalSeconds } |
Measure-Object -average | % Average) }
[pscustomobject] @{ Command = "-contains, pipeline"; $timingPropName =
(1..$($repeat) | % { (Measure-Command { ($paths | Test-Path) -contains $false }).TotalSeconds } |
Measure-Object -average | % Average) }
[pscustomobject] @{ Command = "pipeline, where-object, select -first 1"; $timingPropName =
( 1..$($repeat) | % { (Measure-Command { $paths | Test-Path | ? { $_ -eq $false } | Select-Object -First 1 }).TotalSeconds } |
Measure-Object -average | % Average) }
[pscustomobject] @{ Command = "pipeline, where-object"; $timingPropName =
(1..$($repeat) | % { (Measure-Command { $paths | Test-Path | ? { $_ -eq $false } }).TotalSeconds } |
Measure-Object -average | % Average) }
[pscustomobject] @{ Command = "pipeline, where-object, Test-Path in script block"; $timingPropName =
(1..$($repeat) | % { (Measure-Command { $paths | ? { !(Test-Path $_) } }).TotalSeconds } |
Measure-Object -average | % Average) }
) |
Sort-Object $timingPropName |
Format-Table Command, @{ n=$timingPropName; e={ '{0:.00000}' -f $_.$timingPropName } }