Pages

June 18, 2022

For loop or Foreach, which one is faster in Java?



When I was looking for a job in 2019, one of the questions I was asked was whether we should iterate through an ArrayList using a for or forEach?

The debate over the difference in preference between FOREACH and FOR isn't new. I was under the impression that FOREACH is faster. I eventually realized I was wrong.

FYI, the for-each loop (or enhanced for loop), introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely.

The only practical difference between for and foreach I believe is that in the case of indexable objects, we do not have access to the index. 

for(int i = 0; i < mylist.length; i++) {
   if(i < 5)  {
      //do something
   }  else  {
      //do other stuff
   }
}

However, we can create a separate index int-variable with foreach. e.g:

int index = -1;
for(int myint : mylist)  {
   index++;
   if(index < 5)  {
      //do something
   }  else  {
      //do other stuff
   }
}

Let's write a simple class, which has foreachTest() method that iterates a list using forEach

When we compile this class, the compiler will internally convert this code into an iterator implementation. I have decompiled the compiled code by executing javap -verbose IterateListTest


From the above bytecode we can see, 
a). getfield command is used to obtain the variable integers. 
b). Invoke List.iterator to get the iterator instance 
c). Invoke iterator.hasNext, if it returns true, call iterator.next method.

Let's do a performance test. In the main method of IterateListTest, I have created a list and iterated it using for and forEach loop.


Here are the results:

As we can see, the performance of for loop is better than for-each. Now, let's use LinkedList instead of a ArrayList. You will see the performance of for-each is better for LinkedList.

ArrayList internally uses Arrays to store elements. Since the arrays are contiguous memory spaces, the time complexity is O(1) because data is retrieved through indexes.

LinkedList uses a two-way linked list. When we use for-loop to implement traversal it starts from the head node of the linked list every time that's why the time complexity is O (n*n).

If you enjoy our content and want to support us, please consider donating via  gpay, phonepay or paytm on +91 9920600280. Also, I’d appreciate if you’d buy me a coffee☕ 

https://www.buymeacoffee.com/greekykhs


Keep learning and growing!

-K Himaanshu Shuklaa..

No comments:

Post a Comment