I'm testing branch prediction, the code like this:
//first loop
int sortedSum = 0;
long sortedStartTime = System.nanoTime();
for (int i = 0; i < sortedArray.length; i++) {
if (sortedArray[i] < 0) {
sortedSum += sortedArray[i];
}
}
long sortedTime = System.nanoTime() - sortedStartTime;
//second loop
int randomSum = 0;
long randomStartTime = System.nanoTime();
for (int i = 0; i < randomArray.length; i++) {
if (randomArray[i] < 0) {
randomSum += randomArray[i];
}
}
long randomTime = System.nanoTime() - randomStartTime;
System.out.println("random time: " + randomTime);
System.out.println("sorted time: " + sortedTime);
It's simple print the time about each for loop.
Note that the sortedSum
and randomSum
is assigned in the loop but never accessed.
We don't talk about the branch prediction here, but the output result. The output is:
random time: 32
sorted time: 1595942
Then, I put the second for loop before the first(first randomArray loop, second sortedArray). The output is:
random time: 1541919
sorted time: 40
It seems the JVM doesn't execute the second loop. I decompile the class file, the decompiler doesn't erase anything.
Why? And why JVM DO execute the first loop?
P.S. environment is:
Ubuntu 12.04 LTS
java version "1.7.0_11"
Java(TM) SE Runtime Environment (build 1.7.0_11-b21)
Java HotSpot(TM) 64-Bit Server VM (build 23.6-b04, mixed mode)