Use a for-loop or a for-each loop? [closed]

2019-05-27 09:30发布

问题:

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?

回答1:

Are are same. But some case one is more favourable then others

Case 1:

//for-each loop
for(String name: names){
    log(name);
}

Favourable :

  • When you want to iterate over collection
  • no adding or deletion over array.
  • No need of index of item you iterate

Case 2:

//traditional for-loop
for(int index=0; index < 10; ++index){
    log(names.get(index));
}

Favourable :

  • When you want to iterate over collection
  • you need to work on index of item you iterate. So for that you always have value of index you currently on.

Case 3:

Iterator<String> iter1 = names.iterator();
while (iter1.hasNext()) {
    log(iter1.next());
}

and

//Iterator for loop
for(Iterator<String> iter2 = names.iterator(); iter2.hasNext();){
    log(iter2.next());
}

Favourable :

  • When you want to iterate over collection
  • Addition or deletion take ||ly while iterating.


回答2:

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.



回答3:

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



回答4:

Don't use foreach loop when you want to delete some elements inside this loop. Instead use classic for loop, when you can decrease iterator after removing element from collection.



回答5:

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

http://forums.asp.net/t/1209455.aspx/1


回答6:

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.