Friday, 20 May 2011

ArrayList speed optimization

Lets see how we can increase the speed while processing the ArrayList. The default size for a Java ArrayList class at the initial stage is 10. When an ArrayList operation reaches its maximum capacity which is 10, it increases its capacity by approximately half. A lot of time gets consumed in this case. Lets see why suppose you are adding elements to the ArrayList and if it reaches to 10 then it creates bigger arraylist with size 15 (approx.) and copies both new and old data to it.
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();
}
}

 

Output:

Dynamic array list took (231 mS) to load the data.
Static Array list took (67 mS) to load the data.



No comments:

Post a Comment