Why Enhanced ForLoop take more time over simple loop ?Can you please explain the internal working for Enhanced forloop ? | Core Java Forum
M
mohit thakur Posted on 25/12/2021

Why Enhanced ForLoop take more time over simple loop ?Can you please explain the internal working for Enhanced forloop ?


Y
Yogesh Chawla Replied on 28/12/2021

In the background, Enhanced For loop uses iterator(see below) and Iterator-based loops are slower than indexed based loops.

for (Iterator i=list.iterator(); i.hasNext();)
      i.next();

Reason: Enhanced For loop allocates memory (in the form of an iterator) whereas a normal for loop does not allocate any memory which means that the garbage collector will have to run periodically if you are using enhanced for loop. And many a times, you don't want the garbage collector to run so that's the reason they say when dealing with large numbers(or large/huge data) if you can avoid using enhanced for loop then it should be avoided.

Index Based For Loop:

for (int i=0, n=list.size(); i < n; i++)
    list.get(i);

 

runs faster than enhanced for loop(or for each loop):

for (Iterator i=list.iterator(); i.hasNext();)
      i.next();