Which is Faster For Loop or Foreach in Java

lance
Javarevisited
Published in
3 min readJun 16, 2022

--

You can get some tricks of collection traversal through this article.

There are two ways for Java to traverse collections. One is the most basic for-loop, and the other is the for-each introduced by jdk5. With this method, we can traverse arrays and collections more conveniently. But have you ever thought about these two methods? Which one is more efficient to traverse the collection?

for-each Implementation Principle

Foreach is not a new syntax, but a syntax sugar of Java. At compile time, the compiler will convert this code into an iterator implementation and compile it into bytecode. We can decompile the following compiled code by executing the commandjavap -verbose Testforeach

The detailed bytecode obtained is as follows:

--

--