Pau*_*l π 5 powershell foreach loops continue return
有相当详细的记录表明,foreach 处理速度根据 foreach 循环的执行方式而变化(从最快到最慢排序):
.ForEach()
方法continue
声明,而 #1 没有
return
是如何“continue
使用”.ForEach()
方法时。.ForEach()
太大而难以满足foreach
而您又需要时,正确的使用continue
方法是什么?continue
.ForEach({})
return
在方法内部使用时,您应该注意哪些含义或陷阱.ForEach()
?...在这些情况下,管道的开销使得#3 不再是候选者。
不正确,管道非常高效,它几乎与foreach
(PowerShell 中枚举集合的最快方式)配对。ForEach-Object
是低效的,因为它不提供脚本块。
.ForEach
几乎从来都不是一个好的选择,下面的测试清楚地表明了这一点。此外,输出类型始终为Collection<T>
:
''.ForEach({ }).GetType()
# Namespace: System.Collections.ObjectModel
#
# Access Modifiers Name
# ------ --------- ----
# public class Collection<PSObject>...
Run Code Online (Sandbox Code Playgroud)
.ForEach
不流输出,意味着没有办法提前退出循环Select-Object -First
,这也意味着更高的内存消耗。
Measure-Command {
(0..10).ForEach({ $_; Start-Sleep -Milliseconds 200 }) | Select-Object -First 1
} | ForEach-Object TotalSeconds
# 2.2637483
Run Code Online (Sandbox Code Playgroud)
至于第二个问题,return
是您可以从调用中提前退出的最接近的问题continue
,只要理解它从当前调用中提前退出并转到集合中的下一项,就没有问题,但是有没有真正的方法break
使用循环.ForEach
。
我相信它已经被理解了,但是,break
并且continue
不应该在循环之外使用,switch
, 或trap
:
& {
''.ForEach({ break })
'will never get here'
}
'or here'
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找性能,则应该依赖foreach
带有块的脚本块process
或带有块的函数process
。
& {
''.ForEach({ break })
'will never get here'
}
'or here'
Run Code Online (Sandbox Code Playgroud)