title: Java's varargs performance
body: <p>Coding i came around to check for the vararg performance of Java. </p>
  
  <p>I write following test code:</p>
  
  <pre><code>public class T {
  
      public static void main(String[] args) {
  
          int n = 100000000;
          String s1 = new String("");
          String s2 = new String("");
          String s3 = new String("");
          String s4 = new String("");
          String s5 = new String("");
  
          long t = System.currentTimeMillis();
          for (int i = 0; i &lt; n; i++) {
              foo();
          }
          System.err.println(System.currentTimeMillis() - t);
  
  
          t = System.currentTimeMillis();
          for (int i = 0; i &lt; n; i++) {
              baz(s1, s2, s3, s4, s5);
          }
          System.err.println(System.currentTimeMillis() - t);
  
          t = System.currentTimeMillis();
          for (int i = 0; i &lt; n; i++) {
              bar(s1, s2, s3, s4, s5);
          }
          System.err.println(System.currentTimeMillis() - t);
  
      }
  
      static void foo() {
      }
  
      static void bar(String a1, String a2, String a3, String a4, String a5) {
      }
  
      static void baz(String... a) {
      }
  }
  </code></pre>
  
  <p>On my machine the average output is:</p>
  
  <pre><code>78
  4696
  78
  </code></pre>
  
  <p>Seems that pass variables to methods is at no cost ?! Good !</p>
  
  <p>But using varags is 60x slower ! Why ?</p>
  
  <p>An explanation could be that the program must create the array on the heap and the time is spend by GC. But for less loops i still get as output:</p>
  
  <pre><code>0
  62
  0
  </code></pre>
  
  <p>What is spending this extra time for and anyway the compiler has all information to resolve this to a fix variable call ... </p>
  
  <p>Its not my intention to optimize for that, but i found this curious ...</p>
  
  <p><strong>Update</strong></p>
  
  <p>I added a new test</p>
  
  <pre><code>t = System.currentTimeMillis();
  for (int i = 0; i &lt; n; i++) {
      baz(s1);
  }
  System.err.println(System.currentTimeMillis() - t);
  </code></pre>
  
  <p>And this one argument version is still 30x slower. Maybe there is an ArrayList.toArray() behind the scene ?</p>
  
  <p>So be aware of no-needed varags methods in your code and refactor to fix length. That could be a perfomance boost.</p>