I have a related story. There is a class in commons-math 4.0 called
IntegerRange. Stylistically I much prefer Iterating over such a range than
C style loops and was ready to convert. However I found it many times
slower, at least in not terribly rigorous home micro-benchmarking.

Any good reason why this should be so?
On 16 May 2016 15:14, "sebb" <seb...@gmail.com> wrote:

> 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
>    doSomething(array[i]);
> }
>
> for(Object item : array) { // generic foreach
>   doSomething(item);
> }
>
> 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
> anyway):
>
> int len = array.length; // take array length out of loop
> for(int =0i; i < len; i++ ) { // C-style
>    doSomething(array[i]);
> }
>
> 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: dev-unsubscr...@commons.apache.org
> For additional commands, e-mail: dev-h...@commons.apache.org
>
>

Reply via email to