Uncategorized

Arrays Are Efficient in Java

Here is en example where iterating over an array is much faster than iterating over a list directly. This we can apply if we have to iterate a list over multiple time in a single thread.

private static void checkArrayList() {
ArrayList listOne = new ArrayList();

long startTime = System.nanoTime();
for (int i = 0; i <span id="mce_SELREST_start" style="overflow:hidden;line-height:0;">&#65279;</span>&lt; 1000; i++) {
listOne.add(i);
}
// Total time taken to construct an array list with 1000 elements
System.out.println(&quot;Total Time 1:&quot; + (System.nanoTime() - startTime));

// Iterate entire list
startTime = System.nanoTime();
for (int k : listOne) {

}
// total time to iterate over 1000 elements
System.out.println(&quot;Total Time 2:&quot; + (System.nanoTime() - startTime));

Integer a[] = new Integer[1000];
// Convert list into array
startTime = System.nanoTime();
listOne.toArray(a);
// time to convert list into array
System.out.println(&quot;Total Time 3:&quot; + (System.nanoTime() - startTime));
// Iterate entire array
startTime = System.nanoTime();
for (int k : a) {

}
// total time taken to iterate over array
System.out.println(&quot;Total Time 4:&quot; + (System.nanoTime() - startTime));
}