我一直想知道 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/