For-each loop vs “forEach” method in Java 11. Which one is faster?
Omar Ismail
Senior Software Engineer @ Digitinary | Java & Spring Expert ? | AWS & Microservices Architect ? | FinTech & Open Banking Innovator ?? | Digital Payments Expert ?? | Top 200 IT Content Creator in Jordan ?? | 40K+ ??
Java application
I fill my collections by primitive range from 0 to?N. And then I just iterate over collections using?for-each loop?and?.forEach?method. Also, I use StopWatch (from Apache Commons) to measure time.
Here’s the full code of the app:
Results
N — size of a collection to iterate over.
N = 1,000
N = 100,000
N = 1,000,000
Conclusion
As we can?see,?for-each method exceeds loop in most cases.