Java – Uses enhanced For loop syntax to output slower results

Uses enhanced For loop syntax to output slower results… here is a solution to the problem.

Uses enhanced For loop syntax to output slower results

When I saw this post, I was reading the Google Docs page http://developer.android.com/training/articles/perf-tips.html

Can anyone explain why I get the opposite result?

My result is: (on average)
Results 1: 76
Result 2: 73
Result 3: 143

I ran some tests with the following code (loop to perform the same test):

package TestPack;

import java.util.ArrayList;

public class Test
{
static ArrayList<Integer> mTheArray = new ArrayList<Integer>();
static
{
    for(int i = 0; i < 10000000; i++)
    {
        mTheArray.add(1234234223);
    }
}

static long mTimeStarted;
public static void main(String args[])
{
    Test 1.
    mTimeStarted = System.currentTimeMillis();
    One();
    Fn.Out("Result 1: " + String.valueOf(System.currentTimeMillis() - mTimeStarted));

Test 2.
    mTimeStarted = System.currentTimeMillis();
    Two();
    Fn.Out("Result 2: " + String.valueOf(System.currentTimeMillis() - mTimeStarted));

Test 3
    mTimeStarted = System.currentTimeMillis();
    Three();
    Fn.Out("Result 3: " + String.valueOf(System.currentTimeMillis() - mTimeStarted));

}

Slowest (But not...).
public static int One()
{
    int sum = 0;
    for (int i = 0; i < mTheArray.size(); ++i) 
    {
        sum += mTheArray.get(i);
    }
    return sum;
}

public static int Two()
{
    int sum = 0;
    ArrayList<Integer> localArray = mTheArray;
    int len = localArray.size();

for (int i = 0; i < len; ++i) {
        sum += localArray.get(i);
    }
    return sum;
}

Fastest (But actually slowest in this test).
public static int Three()
{
    int sum = 0;
    for (Integer a : mTheArray) {
        sum += a;
    }
    return sum;
}

Solution

The page you link to clearly states:

With an ArrayList, a hand-written counted loop is about 3x faster
(with or without JIT), but for other collections the enhanced for loop
syntax will be exactly equivalent to explicit iterator usage.

So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration.

You’re using an ArrayList, so the results you get seem to be fairly consistent with this declaration.

Related Problems and Solutions