Should we prefer the for-each loop instead of the traditional for-loops? Is the while-loop advantageous?
List<String> names = Arrays.asList("John", "Jeff", "Mary", "Elise");
//for-each loop
for(String name: names){
log(name);
}
//traditional for-loop
for(int index=0; index < 10; ++index){
log(names.get(index));
}
//Iterator while
Iterator<String> iter1 = names.iterator();
while (iter1.hasNext()) {
log(iter1.next());
}
//Iterator for loop
for(Iterator<String> iter2 = names.iterator(); iter2.hasNext();){
log(iter2.next());
}
What is the best flavor to use?
Don't use
foreach
loop when you want to delete some elements inside this loop. Instead use classicfor
loop, when you can decrease iterator after removing element from collection.Options 1 is just a shorten version of 3 and 4. Out of them #1 is preferrable as it easier to write and read. Option 2 may be better in microperformance as it does not create an Iterator object but only in case you use a RandomAccess list like ArrayList
As long as the container implements Iterable, use
for each
, as long as mentioned above you do not need an index. Altought probablly you will use the Objects id field instead of a for id.Are are same. But some case one is more favourable then others
Case 1:
Favourable :
Case 2:
Favourable :
Case 3:
and
Favourable :
For and foreach differ slightly in performance. They are approximately the same speed. But the foreach loop uses more stack space for local variables.
For more detials about this please refer
Loops 1, 3 and 4 are essentially the same and probably compile to the same bytecode. So use the first one which is more readable.
Loop 2 should be avoided if you don't know what list implementation you are dealing with. In particular,
list.get(i)
can be an O(n) operation on some lists (LinkedLists for example), making the performance of loop 2 an O(n^2) operation = bad.