OckhamsRazor
OckhamsRazor

Reputation: 4906

Optimization on for loops with ArrayLists

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?

Upvotes: 6

Views: 2111

Answers (4)

Erik Živković
Erik Živković

Reputation: 5415

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.

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533492

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)

Upvotes: 7

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

This is a hand-written counted loop. What they mean is that you manually wrote a loop that counts out each element in the array.

for (int i = 0; i < mArray.length; ++i) {

This holds true for arraylists given their underlying implementation. Because the enhanced for loop has to work generically, it cannot assume certain things; such as a index start and end point.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359786

A hand-written counted loop looks like the loops in zero() or one() in that same article:

List<Foo> foos = new ArrayList<Foo>();
// populate the list...

for (int i=0; i<foos.size(); i++) {
    Foo foo = foos.get(i);
    // do something with foo
}

Upvotes: 0

Related Questions