0

Look please at this code:

public static void main(String[] args) {
    String[] array = new String[10000000];
    Arrays.fill(array, "Test");
    long startNoSize;
    long finishNoSize;
    long startSize;
    long finishSize;
    for (int called = 0; called < 6; called++) {
        startNoSize = Calendar.getInstance().getTimeInMillis();
        for (int i = 0; i < array.length; i++) {
            array[i] = String.valueOf(i);
        }
        finishNoSize = Calendar.getInstance().getTimeInMillis();
        System.out.println(finishNoSize - startNoSize);
    }
    System.out.println("Length saved");
    int length = array.length;
    for (int called = 0; called < 6; called++) {
        startSize = Calendar.getInstance().getTimeInMillis();
        for (int i = 0; i < length; i++) {
            array[i] = String.valueOf(i);
        }
        finishSize = Calendar.getInstance().getTimeInMillis();
        System.out.println(finishSize - startSize);
    }
}

The execution result differs from run to run, but there can be observed a strange behavior:

6510
4604
8805
6070
5128
8961
Length saved
6117
5194
8814
6380
8893
3982

Generally, there are 3 result: 6 seconds, 4 seconds, 8 seconds and they iterates in the same order.

Who knows, why does it happen?

UPDATE

After some playing with -Xms and -Xmx Java VM option the next results was observed:

The minimum total memory size should be at least 1024m for this code, otherwise there will be an OutOfMemoryError. The -Xms option influences the time of execution of for block:

It flows between 10 seconds for -Xms16m and 4 seconds for -Xms256m.

The question is - why the initial available memory size affect each iteration and not only the first one ?

Thank you in advance.

StKiller
  • 7,631
  • 10
  • 43
  • 56
  • 1
    Try your program with different heap sizes, and watch the numbers vary in a different pattern. – Ingo Apr 09 '11 at 08:19
  • Thank you very much, Ingo ! Could you please look at the updated question ? – StKiller Apr 09 '11 at 08:57
  • as others have told: it is unpredictable when the GC will kick in - but the higher the memory available, the more chances are it does nothing at all for a small test. – Ingo Apr 09 '11 at 09:01

2 Answers2

2

Micro benchmarking in Java is not that trivial. A lot of things happen in the background when we run a java program; Garbage collection being a prime example. There also might be the case of a context switch from your Java process to another process. IMO, there is no definite explanation why there is a sequence in the seemingly random times generated.

Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93
1

This is not entirely unexpected. There are all sorts of factors that could be affecting your numbers.

See: How do I write a correct micro-benchmark in Java?

Community
  • 1
  • 1
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111