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

Himaanshu Shukla
3 min readJun 18, 2022

--

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 can 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).

Did you know you could give up to 50 claps?
Yes, 50 claps, isn’t it awesome. If you feel my posts are interesting or helpful to you, please do press the 👏 clap button and share/ follow, and help others find this story too. Also, feel free to leave a comment below.

If you enjoyed reading my blogs, I’d appreciate it if you’d buy me a coffee

Keep learning and growing!
- Himanshu Shukla..

--

--

Himaanshu Shukla

Software Engineer | Certified Scrum Master | Angel Therapy Practitioner| Light Worker| Empath | Buy me a coffee https://ko-fi.com/greekykhs |Blogger