commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From sebb <>
Subject [ALL] Performance of foreach loop with arrays.
Date Mon, 16 May 2016 13:13:55 GMT
Looking for feedback on C-style and foreach() loops when using arrays.
[This email does not consider collections; please start another thread
if you want to discuss that.]

TLDR; Always use foreach() with arrays unless you need access to the index.


There are two main ways to iterate over an array:

for(int i=0; i < array.length; i++ ) { // C-style

for(Object item : array) { // generic foreach

The JVM has special instructions to load/store items from arrays;
different instructions are used for Objects and each primitive type;
these instructions only require the array start address and the index.

There have been suggestions that the for loop is less efficient
because it creates an iterator which needs to be garbage collected.

AFAICT in the case of *arrays* there is absolutely no need for the
compiler to create an iterator (or indeed any other temporary object)
in order to support the foreach() loop.

Experiments with javap confirm this.

IMO the only reason to prefer the C-style loop is where the index is
needed for something else in the loop.

Otherwise the foreach() loop seems much better to me:
- simpler to code and read
- cannot accidentally use the wrong index or wrong index comparison

Also the C-style loop evaluates the index each time through the loop;
one needs to code it as below to avoid this (the optimiser may do this

int len = array.length; // take array length out of loop
for(int =0i; i < len; i++ ) { // C-style

This is even messier and more prone to error.

Note: javap does show an extra astore/aload instruction pair in the
test loop prior to calling doSomething() in the foreach() case. Those
appear to be superfluous and will presumably be optimised away at
runtime. A later compiler will likely fix this. In any case the
overhead of two local memory accesses is miniscule.

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message