Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-each vs for vs while

I wonder what is the best way to implement a "for-each" loop over an ArrayList or every kind of List.

Which of the followings implementations is the best and why? Or is there a best way?

Thank you for your help.


List values = new ArrayList();

values.add("one"); values.add("two"); values.add("three"); ...

//#0
for(String value : values) { ... }

//#1
for(int i = 0; i < values.size(); i++) { String value = values.get(i); ... }

//#2
for(Iterator it = values.iterator(); it.hasNext(); ) { String value = it.next(); ... }

//#3
Iterator it = values.iterator(); while (it.hasNext()) { String value = (String) it.next(); ... }

like image 491
Michaël Avatar asked Dec 05 '10 00:12

Michaël


People also ask

Do While VS for each?

do... while − loops through a block of code once, and then repeats the loop as long as a special condition is true. foreach − loops through a block of code for each element in an array.

Which one is faster for or foreach or while?

Correctly used, while is the fastest, as it can have only one check for every iteration, comparing one $i with another $max variable, and no additional calls before loop (except setting $max) or during loop (except $i++; which is inherently done in any loop statement).

Is for each better than for loop?

The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access.


2 Answers

#3 has a disadvantage because the scope of the iterator it extends beyond the end of the loop. The other solutions don't have this problem.

#2 is exactly the same as #0, except #0 is more readable and less prone to error.

#1 is (probably) less efficient because it calls .size() every time through the loop.

#0 is usually best because:

  • it is the shortest
  • it is least prone to error
  • it is idiomatic and easy for other people to read at a glance
  • it is efficiently implemented by the compiler
  • it does not pollute your method scope (outside the loop) with unnecessary names
like image 83
Greg Hewgill Avatar answered Oct 07 '22 19:10

Greg Hewgill


The short answer is to use version 0. Take a peek at the section title Use Enhanced For Loop Syntax at Android's documentation for Designing for Performance. That page has a bunch of goodies and is very clear and concise.

like image 32
Andrew White Avatar answered Oct 07 '22 21:10

Andrew White