I was doing some performance testing regarding object allocation, when I came across a weird result. I have the following java code:
public static long TestMethod(){
int len = 10000000;
Object[] obs = new Object[len];
long t = System.nanoTime();
for (int i = 0; i < len; i++) {
obs[i] = new Object();
}
return System.nanoTime() - t;
}
public static void main(String... args) throws InterruptedException {
for(int i = 0; i < 10; i++){
System.gc();
System.gc();//Wait for the gc to be finished
Thread.sleep(1000);
System.out.println(TestMethod());
}
}
Expectation: First call will be slower then second call, due to requesting a larger memory space from the operating system and hotspot enhancements. But second and third will be nearly the same.
Observed result:
11284734000
799837000
682304000
304736000
380770000
392786000
374279000
381611000
379174000
407256000
Still a considerable speed up between the third and fourth iteration. What causes this speedup? How can I be sure my measurements are accurate when testing other functions, do I have to call the function more than four times before measuring?