当我遇到一个奇怪的结果时,我正在做一些关于对象分配的性能测试.我有以下
java代码:
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());
}
}
期望:
由于请求操作系统和热点增强的更大内存空间,第一次调用将比第二次调用慢.但第二和第三将几乎相同.
观察结果:
11284734000
799837000
682304000
304736000
380770000
392786000
374279000
381611000
379174000
407256000
在第三次和第四次迭代之间仍然有相当大的加速.是什么导致这种加速?在测试其他功能时,如何确保测量结果准确无误,在测量之前是否必须调用该功能四次以上?