title: array of structures, or structure of arrays?
body: <p>Hmmm. I have a table which is an array of structures I need to store in Java. The naive don't-worry-about-memory approach says do this:</p>
  
  <pre><code>public class Record {
    final private int field1;
    final private int field2;
    final private long field3;
    /* constructor &amp; accessors here */
  }
  
  List&lt;Record&gt; records = new ArrayList&lt;Record&gt;();
  </code></pre>
  
  <p>If I end up using a large number (> 10<sup>6</sup> ) of records, where individual records are accessed occasionally, one at a time, how would I figure out how the preceding approach (an ArrayList) would compare with an optimized approach for storage costs:</p>
  
  <pre><code>public class OptimizedRecordStore {
    final private int[] field1;
    final private int[] field2;
    final private long[] field3;
  
    Record getRecord(int i) { return new Record(field1[i],field2[i],field3[i]); }
    /* constructor and other accessors &amp; methods */
  }
  </code></pre>
  
  <p><strong>edit:</strong></p>
  
  <ul>
  <li>assume the # of records is something that is changed infrequently or never</li>
  <li>I'm probably not going to use the OptimizedRecordStore approach, but I want to understand the storage cost issue so I can make that decision with confidence.</li>
  <li>obviously if I add/change the # of records in the OptimizedRecordStore approach above, I either have to replace the whole object with a new one, or remove the "final" keyword.</li>
  <li>kd304 brings up a good point that was in the back of my mind. In other situations similar to this, I need column access on the records, e.g. if field1 and field2 are "time" and "position", and it's important for me to get those values as an array for use with MATLAB, so I can graph/analyze them efficiently.</li>
  </ul>