title: Why does the first method call always take the longest?
body: <p>After reading about similar topics on Stack Overflow, I wrote the following code to get an idea about how consistent <code>System.nanoTime()</code> is.  </p>
  
  <p>It simply calls <code>System.nanoTime()</code> before and after a method call to an empty void function, recording the elapsed time in the process. As you can see in the results, however, the first call always take the longest. What is the reason for this?</p>
  
  <pre><code>public class Test {
      public static void main(String[] args) {
          for(int i = 0; i &lt; 10; i++) {
              double start = System.nanoTime();
              foo();
              double end = System.nanoTime();
              double diff = end - start;
              System.out.println("Diff: " + diff);
          }
      }
  
      public static void foo() {
  
      }
  }
  </code></pre>
  
  <p>Results:</p>
  
  <pre><code>Diff: 2765.0
  Diff: 509.0
  Diff: 236.0
  Diff: 238.0
  Diff: 230.0
  Diff: 539.0
  Diff: 359.0
  Diff: 356.0
  Diff: 380.0
  Diff: 353.0
  </code></pre>
  
  <p>Note that I did read this question: <a href="https://stackoverflow.com/questions/2608763/why-does-first-call-to-java-io-file-createtempfilestring-string-file-take-5-se">Why does first call to java.io.File.createTempFile(String,String,File) take 5 seconds on Citrix?</a></p>
  
  <p>Also, this link is helpful for future reference, but doesn't necessarily answer my specific question: <a href="https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java">How do I write a correct micro-benchmark in Java?</a></p>