I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ?
Since arrays keep
I agree that in most cases you should choose the flexibility and elegance of ArrayLists over arrays - and in most cases the impact to program performance will be negligible.
However, if you're doing constant, heavy iteration with little structural change (no adds and removes) for, say, software graphics rendering or a custom virtual machine, my sequential access benchmarking tests show that ArrayLists are 1.5x slower than arrays on my system (Java 1.6 on my one year-old iMac).
Some code:
import java.util.*;
public class ArrayVsArrayList {
static public void main( String[] args ) {
String[] array = new String[300];
ArrayList list = new ArrayList(300);
for (int i=0; i<300; ++i) {
if (Math.random() > 0.5) {
array[i] = "abc";
} else {
array[i] = "xyz";
}
list.add( array[i] );
}
int iterations = 100000000;
long start_ms;
int sum;
start_ms = System.currentTimeMillis();
sum = 0;
for (int i=0; i