For-each loop vs “forEach” method in Java 11. Which one is faster?

For-each loop vs “forEach” method in Java 11. Which one is faster?

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:

No alt text provided for this image

Results

N — size of a collection to iterate over.


N = 1,000

No alt text provided for this image
No alt text provided for this image

N = 100,000

No alt text provided for this image
No alt text provided for this image

N = 1,000,000


No alt text provided for this image
No alt text provided for this image

Conclusion

As we can?see,?for-each method exceeds loop in most cases.






要查看或添加评论,请登录

Omar Ismail的更多文章

社区洞察

其他会员也浏览了