As per suggestions from the Android Documentation the most efficient ways for making loop are:
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
public void two() {
int sum = 0;
for (Foo a : mArray) {
sum += a.mSplat;
}
}
Please, note that these ways have same performance for devices with JIT. So, in cases then JIT is off (e.g. while debugging using Eclipse) You might observe different results (two() will be faster than one())
Update
I've checked ArrayLists also by using the following code:
final ArrayList<String> testArrayList = new ArrayList<String>(1000);
for (int i = 0; i < 1000; i++) {
testArrayList.add(String.valueOf(i<<2));
}
final TimingLogger timings = new TimingLogger("Loop", "ArrayLists");
timings.addSplit("start");
for (int loopCount = 0; loopCount < 1000; loopCount++) {
int sum = 0;
for (int i = 0; i < testArrayList.size(); i++) {
sum += Integer.valueOf(testArrayList.get(i));
}
}
timings.addSplit("zero()");
for (int loopCount = 0; loopCount < 1000; loopCount++) {
int sum = 0;
final int len = testArrayList.size();
for (int i = 0; i < len; i++) {
sum += Integer.valueOf(testArrayList.get(i));
}
}
timings.addSplit("one()");
for (int loopCount = 0; loopCount < 1000; loopCount++) {
int sum = 0;
for (String item : testArrayList) {
sum += Integer.valueOf(item);
}
}
timings.addSplit("two()");
timings.dumpToLog();
And obtained the following output (with JIT):
ArrayLists: begin
ArrayLists: 0 ms, start
ArrayLists: 2713 ms, zero()
ArrayLists: 1753 ms, one()
ArrayLists: 1922 ms, two()
ArrayLists: end, 6388 ms
So, we able to see, that variants one() and two() provides similar results, and these results are faster than zero() (so, results look similar to ones described in the documentation for arrays).