title: Slow initialization of large array of small objects
body: <p>I've stumbled upon this case today and I'm wondering what is the reason behind this huge difference in time.</p>
  
  <p>The first version initializes an 5k x 5k array of raw ints:</p>
  
  <pre><code>public void initializeRaw() {
    int size = 5000;
    int[][] a = new int[size][size];
    for (int i = 0; i &lt; size; i++)
      for (int j = 0; j &lt; size; j++)
        a[i][j] = -1;
  }
  </code></pre>
  
  <p>and it takes roughly 300ms on my machine.
  On the other hand, initializing the same array with simple 2-int structs:</p>
  
  <pre><code>public class Struct { public int x; public int y; }
  
  public void initializeStruct() {
    int size = 5000;
    Struct[][] a = new Struct[size][size];
    for (int i = 0; i &lt; size; i++)
      for (int j = 0; j &lt; size; j++)
        a[i][j] = new Struct();
  }
  </code></pre>
  
  <p>takes over 15000ms.</p>
  
  <p>I would expect it to be a bit slower, after all there is more memory to allocate (10 bytes instead of 4 if I'm not mistaken), but I cannot understand why could it take 50 times longer.</p>
  
  <p>Could anyone explain this? Maybe there is just a better way to to this kind of initialization in Java?</p>
  
  <p>EDIT: For some comparison - the same code that uses Integer instead of int/Struct works 700ms - only two times slower.</p>