title: java ArrayList initial capacity performance effect
body: <p>I have in my java app a loop that adds object arrays into a list</p>
  
  <pre><code>List&lt;Object[]&gt; list = new ArrayList&lt;Object[]&gt;();
  </code></pre>
  
  <p>I noticed that NOT giving an initial capacity was actually faster than giving the capacity.</p>
  
  <p>I have a 23 seconds  vs 15 seconds difference.</p>
  
  <p>I've created this dummy JUnit test to mock that and go 6 seconds vs 6.7 seconds difference, favoring the NO initial capacity:</p>
  
  <pre><code>@Test
  public void asdf() {
  
      int rowSize = 20;
      int rowCount = 10000000;
  
      // DATA PREP
      int[][] matrix = new int[rowCount][];
      for (int i=0; i&lt; matrix.length; i++) {
  
          matrix[i] = new int[rowSize];
          for (int j=0; j&lt; rowSize; j++) {
              matrix[i][j] = (int) (Math.random()*10);
          }
      }
  
      BiFunction&lt;Integer, Integer, Object&gt; getValue = new BiFunction&lt;Integer, Integer, Object&gt;() {
          @Override
          public Object apply(Integer row, Integer col) {
              return matrix[row][col];
          }
      };
  
      //END DATA PREP
  
      long start = System.currentTimeMillis();
  
      // THIS IS THE DIFFERENCE!!!!
      //List&lt;Object[]&gt; lst = new ArrayList&lt;&gt;(rowCount);
      List&lt;Object[]&gt; lst = new ArrayList&lt;&gt;();
  
      for (int i = 0; i &lt; rowCount; i++) {
          Object[] row = new Object[rowSize];
  
          for (int j = 0; j &lt; rowSize; j++) {
              row[j] = getValue.apply(i, j);
          }
  
          lst.add(row);
      }
  
      long totalTime = System.currentTimeMillis() - start;
  
      System.out.println(totalTime);
  }     
  </code></pre>
  
  <p>How does it make any sense?</p>
  
  <p>I know generally this code is crap, It's just trying to mock my real case, reading off a resultset (not the jdbc one).</p>
  
  <p>Thanks!</p>