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?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With