So if we are knowing the size in advance then it is very useful to initialize the arraylist with that size to avoid performance overhead.
Lets see how much difference it makes if specify initial size in advance.
public class ArrayListSpeedTest {
private static int size = 5000000;
public ArrayListSpeedTest() {
ArrayList dynamicArrayList = new ArrayList();
ArrayList staticArrayList = new ArrayList(size);
// Lets check how much time it took to load dynamic arraylist size.
long start = System.currentTimeMillis();
loadData( dynamicArrayList );
System.out.println("Dynamic array list took ("+ (System.currentTimeMillis()-start)+ " mS) to load the data.");
// sLets check how much time it took to load static arraylist size.
start = System.currentTimeMillis();
loadData( staticArrayList );
System.out.println("Static Array list took (" +(System.currentTimeMillis()-start) +" mS) to load the data.");
}
private void loadData(ArrayList target) {
for(int i=0; i< size; i ++ ) {
target.add(" test ");
}
}
public static void main(String[] args){
new ArrayListSpeedTest();
}
}
Dynamic array list took (231 mS) to load the data.
Static Array list took (67 mS) to load the data.