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++) {
// 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();
// 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));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s