That is opposite of my testing:...
The 'foreach' is consistently faster. The time difference is
independent of the size of the array. What I know about JVM
implementations, the foreach version SHOULD always be faster -
because the no bounds checking needs to be done on the element access...
Times for the client JVM under 1.5_13
N = 10
indexed time = 14
foreach time = 8
N = 100
indexed time = 90
foreach time = 75
N = 1000
indexed time = 875
foreach time = 732
N = 10000
indexed time = 8801
foreach time = 7552
N = 100000
indexed time = 88566
foreach time = 75974
Times for the server JVM under 1.5_13
N = 10
indexed time = 21
foreach time = 21
N = 100
indexed time = 85
foreach time = 32
N = 1000
indexed time = 347
foreach time = 303
N = 10000
indexed time = 3472
foreach time = 3017
N = 100000
indexed time = 34158
foreach time = 30133
package test;
import junit.framework.TestCase;
public class LoopTest extends TestCase {
public void testLoops() {
int I = 100000;
int N = 10;
for (int factor = 0; factor < 5; factor++) {
String[] strings = new String[N];
for (int i = 0; i < N; i++) {
strings[i] = "some string";
}
System.out.println("N = " + N);
long len = 0;
long start = System.currentTimeMillis();
for (int i = 0; i < I; i++) {
for (int j = 0; j < N; j++) {
len += strings[j].length();
}
}
System.out.println("indexed time = " + (System.currentTimeMillis
() - start));
len = 0;
start = System.currentTimeMillis();
for (int i = 0; i < I; i++) {
for (String s : strings) {
len += s.length();
}
}
System.out.println("foreach time = " + (System.currentTimeMillis
() - start));
N *= 10;
}
}
}