Fwd: No for each loop comment?

Andrew Haley aph at redhat.com
Mon Sep 29 15:21:55 UTC 2014


On 09/29/2014 03:29 PM, Paul Benedict wrote:
> Open JDKers, I am forwarding an email to get some clarification. It's been
> a common understanding that foreach should perform no differently than the
> equivalent for-loop . However, some fellow developers claim there is a
> noticable difference in their microbenchmarking. Can you help explain what
> is really going on? It's either the case there is a true difference (a
> result that would surprise me) or the results are within a margin of error
> that make the results insignificant. Please advise.

The actual code that such a forEach loop generates is this:

    private int forLoop(final int[] array) {
        int result = 0;
        int[] a = array;
        int len = a.length;
        for (int i = 0; i < len; i++) {
            int element = a[i];
            result ^= element;
        }
        return result;
    }

If you get different timings for this one, then the measurements are
suspect.

Java microbenchmarking is notoriously difficult.  Please try to use
jmh; you'll get better and easier to interpret results.

Andrew.


http://openjdk.java.net/projects/code-tools/jmh/




More information about the core-libs-dev mailing list