title: C#: Why is a function call faster than manual inlining?
body: <p>I have measured the execution time for two ways of calculating the power of 2:</p>
  
  <p><strong>1) Inline</strong></p>
  
  <pre><code>result = b * b;
  </code></pre>
  
  <p><strong>2) With a simple function call</strong></p>
  
  <pre><code>result = Power(b);
  </code></pre>
  
  <p>When running in Debug mode, everything is as expected: Calling a function is considerably more expensive than doing the calculation in line (385 ms in line vs. 570 ms function call).</p>
  
  <p>In release mode, I'd expect the compiler to speed up execution time of the function call considerably because the compiler would inline internally the very small <code>Power()</code> function. But I'd NOT expect the function call to be FASTER than the manual inlined calculation.</p>
  
  <p>Most astonishingly this is the case: In the release build, the first run needs 109 ms and the second run with the call to <code>Power()</code> needs only 62 ms.</p>
  
  <p><strong>How can a function call be faster than manual inlining?</strong></p>
  
  <p>Here is the program for your reproduction:</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine("Starting Test");
  
          // 1. Calculating inline without function call
          Stopwatch sw = Stopwatch.StartNew();
  
          for (double d = 0; d &lt; 100000000; d++)
          {
              double res = d * d;
          }
  
          sw.Stop();
          Console.WriteLine("Checked: " + sw.ElapsedMilliseconds);
  
          // 2. Calulating power with function call
          Stopwatch sw2 = Stopwatch.StartNew();
  
          for (int d = 0; d &lt; 100000000; d++)
          {
              double res = Power(d);
          }
  
          sw2.Stop();
          Console.WriteLine("Function: " + sw2.ElapsedMilliseconds);
  
          Console.ReadKey();
      }
  
      static double Power(double d)
      {
          return d * d;
      }
  }
  </code></pre>