title: PowerShell functions and performance
body: <p>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.</p>
  
  <pre><code>$ranGen = New-Object System.Random
  </code></pre>
  
  <p>Executing</p>
  
  <pre><code>for ($i = 0; $i -lt 100000; $i++) {
      $void = $ranGen.Next()
  }
  </code></pre>
  
  <p>finishes within 0.19 seconds.
  I put the call inside a function </p>
  
  <pre><code>Get-RandomNumber {
      param( $ranGen )
  
      $ranGen.Next()
  }
  </code></pre>
  
  <p>Executing</p>
  
  <pre><code>for ($i = 0; $i -lt 100000; $i++) {
      $void = Get-RandomNumber $ranGen
  }
  </code></pre>
  
  <p>takes about 4 seconds.</p>
  
  <p>Why is there such a huge performance impact?</p>
  
  <p>Is there a way I can use functions and still get the performance I have with the direct call?</p>
  
  <p>Are there better (more performant) ways of code encapsulation in PowerShell?</p>