To test the effect of locality on program's running time, I wrote a program as below.
public class Locality {
private char[] value = new char[LOOP_COUNT * 4];
int count = 0;
private static final int LOOP_COUNT = 100000000;
public void appendNull() {
int c = count;
foo();
final char[] value = this.value;
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
count = c;
}
public void appendNullNonLocality() {
int c = count;
foo();
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
count = c;
}
private void foo() {
int i = 0;
i++;
}
public static void main(String[] args) {
Locality
locality = new Locality(),
locality1 = new Locality();
long start, end;
start = System.currentTimeMillis();
for (int i = 0; i < LOOP_COUNT; i++) {
locality.appendNullNonLocality();
}
end = System.currentTimeMillis();
System.out.println("without locality, the run time is : " + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < LOOP_COUNT; i++) {
locality1.appendNull();
}
end = System.currentTimeMillis();
System.out.println("with locality, the run time is : " + (end - start));
}
}
Without invoking foo
in appendNull
and appendNullNonLocality
, appendNull
is faster than appendNullNonLocality
, just as what I guessed. But when I invoke foo
in appendNull
and appendNullNonLocality
, appendNull
is slower than appendNullNonLocality
. So I am confused by this. Can anybody explain the reason for me?.
note: I run the program with the JVM parameter -Djava.compiler=NONE
to avoid JIT optimizations.