I've been wondering about the performance impact of functions in PowerShell. Let's say we want to generate 100.000 random numbers using System.Random.
$ranGen = New-Object System.Random
Executing
for ($i = 0; $i -lt 100000; $i++) {
$void = $ranGen.Next()
}
finishes within 0.19 seconds. I put the call inside a function
Get-RandomNumber {
param( $ranGen )
$ranGen.Next()
}
Executing
for ($i = 0; $i -lt 100000; $i++) {
$void = Get-RandomNumber $ranGen
}
takes about 4 seconds.
Why is there such a huge performance impact?
Is there a way I can use functions and still get the performance I have with the direct call?
Are there better (more performant) ways of code encapsulation in PowerShell?