Consider the following scenario.
List list = new ArrayList<>();
Now I added the String values for this li
Simple answers: No and no.
Internally the for-each loop creates an Iterator to iterate through the collection.
The advantage of using the Iterator explicitly is that you can access the Iterators method.
Here is simple code snippet to check the performance of For-each vs Iterator vs for for the traversal of ArrayList<String>, performed on Java version 8.
long MAX = 2000000;
ArrayList<String> list = new ArrayList<>();
for (long i = 0; i < MAX; i++) {
list.add("" + i);
}
/**
* Checking with for each iteration.
*/
long A = System.currentTimeMillis();
for (String data : list) {
// System.out.println(data);
}
long B = System.currentTimeMillis();
System.out.println(B - A + "ms");
/**
* Checking with Iterator method
*/
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
// System.out.println(iterator.next());
}
long C = System.currentTimeMillis();
System.out.println(C - B + "ms");
/**
* Checking with normal iteration.
*/
for (int i = 0; i < MAX; i++) {
list.get((int) (i % (MAX - i)));
// System.out.println(list.get(i));
}
long D = System.currentTimeMillis();
System.out.println(D - C + "ms");
Average Output values:
19ms
9ms
27ms
Result Analysis:
Iterator(9ms) <For-each(19ms) <For(27ms)Here
Iteratorhas the best performance andForhas the least performance. HoweverFor-eachperformance lies somewhere in between.