If you are iterating a class implementing the List interface the regular for loop will get the next element with list.get(I), the for each will internally use an Iterator and call iterator.next(). This has a a huge impact on the speed of a loop with some classes.
A small example:
LinkedList<Integer> list = new LinkedList<>();
for (int i = 0; i < 100_000; i++) list.add(i);
int doNothing = 0;
long start1 = System.nanoTime(), end1;
for (int i = 0; i < list.size(); i++) doNothing+= list.get(i);
end1 = System.nanoTime();
System.out.println(end1-start1);
doNothing = 0;
long start2 = System.nanoTime(), end2;
for(Integer i : list) doNothing+= i;
end2 = System.nanoTime();
System.out.println(end2-start2);
the output on my machine:
3460558170 //nanoseconds regular
2178261 //nanoseconds for each ~1000 times as fast in this specific example
The reason why the for each loop is that much faster is, that when it has the first element, it directly jumps to the next one and processes the next node.
In LinkedList class each inserted object represented by a node that remembers the next node. So it performs in O(n).
foreach uses iterator
*
*
*
*
*
In a a normal loop when list.get(i) is called it will start from the beginning and jump from node to node i times. When the list is long, it will take some time. When this is done in a loop, the performance is in O(n²).
regular for list.get(i)
*
**
***
****
*****
Sometimes you have the case that you just know, that a List - Interface is returned by a method call. If it returns a long LinkedList and you use a normal fori the inpact on the performance could be huge.
Try the code I posted and vary the length of the list to check the difference.