0

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.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • I tried running your example and the differences are so small as to be basically irrelevant. – Federico klez Culloca May 08 '20 at 10:29
  • 2
    Read [this](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). Your measurements are more or less useless there. – akuzminykh May 08 '20 at 10:32
  • How many runs of your code did you do? Are results always the same? Are you sure the differences are not due to non-jvm background process? – M. Prokhorov May 08 '20 at 10:38
  • 1
    @akuzminykh Thanks for your link. I realised I had few knowledge of how to write usefull benchmark after reading it. – larryzhang May 09 '20 at 03:34

0 Answers0