Invoke-Command faster than the command itself?

有些话、适合烂在心里 提交于 2019-11-29 04:34:01

As it turns out, based on feedback from a PowerShell team member on this related GitHub issue, the issue is more generally about (implicit) dot-sourcing (such as direct invocation of an expression) vs. running in a child scope, such as with &, the call operator, or, in the case at hand, with Invoke-Command -ScriptBlock.

Running in a child scope avoids variable lookups that are performed when (implicitly) dot-sourcing.

Therefore, as of Windows PowerShell v5.1 / PowerShell Core 6.2, you can speed up side-effect-free expressions by simply invoking them via & { ... }, in a child scope (somewhat counter-intuitively, given that creating a new scope involves extra work):

That is, this optimization can be used with expressions that aren't expected to modify the caller's variables (directly).

The following simplified code, which uses a foreach expression to loop 1 million times (1e6) demonstrates this:

# REGULAR, direct invocation of an expression (a `foreach` statement in this case), 
# which is implicitly DOT-SOURCED
(Measure-Command { $result = foreach ($n in 1..1e6) { $n } }).TotalSeconds

# OPTIMIZED invocation in CHILD SCOPE, using & { ... }
# 10+ TIMES FASTER.
(Measure-Command { $result = & { foreach ($n in 1..1e6) { $n } } }).TotalSeconds
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!