PowerShell 功能和性能

标签 powershell

我一直想知道 PowerShell 中函数对性能的影响。
假设我们想使用 System.Random 生成 100.000 个随机数。

$ranGen = New-Object System.Random

执行
for ($i = 0; $i -lt 100000; $i++) {
    $void = $ranGen.Next()
}

在 0.19 秒内完成。
我把调用放在一个函数中
Get-RandomNumber {
    param( $ranGen )

    $ranGen.Next()
}

执行
for ($i = 0; $i -lt 100000; $i++) {
    $void = Get-RandomNumber $ranGen
}

大约需要 4 秒。

为什么会有如此巨大的性能影响?

有没有办法可以使用函数并仍然获得直接调用的性能?

PowerShell 中是否有更好(更高性能)的代码封装方式?

最佳答案

函数调用很昂贵。解决这个问题的方法是尽可能多地放入函数中。看看下面...

$ranGen = New-Object System.Random
$RepeatCount = 1e4

'Basic for loop = {0}' -f (Measure-Command -Expression {
    for ($i = 0; $i -lt $RepeatCount; $i++) {
        $Null = $ranGen.Next()
    }
    }).TotalMilliseconds

'Core in function = {0}' -f (Measure-Command -Expression {
function Get-RandNum_Core {
    param ($ranGen)
    $ranGen.Next()
    }

    for ($i = 0; $i -lt $RepeatCount; $i++) {
        $Null = Get-RandNum_Core $ranGen
    }
    }).TotalMilliseconds

'All in function = {0}' -f (Measure-Command -Expression {
    function Get-RandNum_All {
        param ($ranGen)
        for ($i = 0; $i -lt $RepeatCount; $i++) {
            $Null = $ranGen.Next()
            }
        }
    Get-RandNum_All $ranGen
    }).TotalMilliseconds

输出 ...
Basic for loop = 49.4918
Core in function = 701.5473
All in function = 19.5579

从我隐约记得[并且无法再次找到],经过一定次数的重复后,函数 scriptblock 得到 JIT-ed ......这似乎是速度的来源。

关于PowerShell 功能和性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54434601/

相关文章:

来自另一个 RunBook 的 Azure 自动化 RunBook

regex - 分割 CSV 文件中的字符串

powershell - 无法删除带有尾随空格的 Windows 7 上的文件夹

powershell - 如何使用 envdte 创建嵌套的解决方案文件夹

windows - 规避路径长度限制

arrays - 从 powershell 数组/集合/哈希表中删除一行

powershell - 使用 powershell 从 Azure 获取经典 VM 的虚拟机位置

powershell - 如何从文件名中删除文件扩展名

powershell - 如何从 PowerShell 运行 SQL Server 查询?

regex - PowerShell:拆分字符串而不删除拆分模式?