Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization on for loops with ArrayLists

Tags:

java

arraylist

From this article,

hand-written counted loop is about 3x faster

than an enhanced for loop for iterating over arraylists.

Firstly, what do they mean by "hand-written counted loop"? They didn't explicitly elaborate what this means. Secondly, why is it that this holds true only for arraylists and not the other collections?

like image 984
OckhamsRazor Avatar asked Apr 11 '12 20:04

OckhamsRazor


2 Answers

Firstly, what do they mean by "hand-written counted loop"?

I assume they mean

for(int i=0;i<list.size();i++) {
    list.get(i);
}

Secondly, why is it that this holds true only for arraylists and not the other collections?

ArrayList supports efficient random access and removing the Iterator can make a small improvement. (or a large relative improvement if you have a loop which doesn't do anything else)

For other collections e.g. LinkedList, it faster to use an Iterator because get(n) is slower. For Set there is no get(n)

like image 191
Peter Lawrey Avatar answered Sep 21 '22 12:09

Peter Lawrey


All the answers to this question (at the time of me writing this there are three answers), are wrong.

For Android you should NOT do this for hand written loops!

for(int i=0;i<list.size();i++) {
    list.get(i);
}

ABOVE IS WRONG!

The loop must look like this (size is temporarily copied into its own variable):

int size = list.size();
for(int i=0;i<size;i++) {
    list.get(i);
}

Otherwise there will be a lookup penalty for each iteration of the loop! If you read the article linked from the question carefully, you will see that google recommends this pattern as well.

like image 36
Erik Zivkovic Avatar answered Sep 19 '22 12:09

Erik Zivkovic