+ 1

Enhanced for loop vs. for loop

i would like to know, if enhanced for loop doesnt allow changes in the elements of the array, that means, it uses less memory, and it is faster?

19th Apr 2017, 12:50 PM
Benedek Måté Tóth
Benedek Måté Tóth - avatar
2 Answers
+ 6
The first thing to note is that for collections the enhanced for loop uses an Iterator, so if you manually iterate over a collection using an Iterator then you should have pretty much the same performance than the enhanced for loop. One place where the enhanced for loop is faster than a naively implemented traditional loop is something like this: LinkedList<Object> list = ...; // Loop 1: int size = list.size(); for (int i = 0; i<size; i++) { Object o = list.get(i); /// do stuff } // Loop 2: for (Object o : list) { // do stuff } // Loop 3: Iterator<Object> it = list.iterator(); while (it.hasNext()) { Object o = it.next(); // do stuff } In this case Loop 1 will be slower than both Loop 2 and Loop 3, because it will have to (partially) traverse the list in each iteration to find the element at position i. Loop 2 and 3, however will only ever step one element further in the list, due to the use of an Iterator. Loop 2 and 3 will also have pretty much the same performance since Loop 3 is pretty much exactly what the compiler will produce when you write the code in Loop 2.
19th Apr 2017, 1:32 PM
Sathish Kumar
Sathish Kumar - avatar
0
thank you for the explanation!
19th Apr 2017, 4:32 PM
Benedek Måté Tóth
Benedek Måté Tóth - avatar