[英]Why does the first method call always take the longest?
After reading about similar topics on Stack Overflow, I wrote the following code to get an idea about how consistent System.nanoTime()
is. 在阅读Stack Overflow上的类似主题后,我编写了以下代码以了解System.nanoTime()
一致性。
It simply calls System.nanoTime()
before and after a method call to an empty void function, recording the elapsed time in the process. 它只是在方法调用空void函数之前和之后调用System.nanoTime()
,记录进程中的已用时间。 As you can see in the results, however, the first call always take the longest. 但是,正如您在结果中看到的那样,第一次调用总是花费最长的时间。 What is the reason for this? 这是什么原因?
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
double start = System.nanoTime();
foo();
double end = System.nanoTime();
double diff = end - start;
System.out.println("Diff: " + diff);
}
}
public static void foo() {
}
}
Results: 结果:
Diff: 2765.0
Diff: 509.0
Diff: 236.0
Diff: 238.0
Diff: 230.0
Diff: 539.0
Diff: 359.0
Diff: 356.0
Diff: 380.0
Diff: 353.0
Note that I did read this question: Why does first call to java.io.File.createTempFile(String,String,File) take 5 seconds on Citrix? 请注意,我确实读过这个问题: 为什么首先在Citrix上调用java.io.File.createTempFile(String,String,File)需要5秒?
Also, this link is helpful for future reference, but doesn't necessarily answer my specific question: How do I write a correct micro-benchmark in Java? 此外,此链接有助于将来参考,但不一定能回答我的具体问题: 如何在Java中编写正确的微基准测试?
JVM performs Class Resolution (see JVMS 5.4.3 ) lazily. JVM懒洋洋地执行类解析(参见JVMS 5.4.3 )。 In your case the symbolic reference to foo
in the constant pool is resolved on the first execution of invokestatic
bytecode, ie on the first invocation of the method. 在您的情况下,常量池中foo
的符号引用在第一次执行invokestatic
字节码时解析,即在方法的第一次调用时解析。 Obviously, it takes more time than just executing an already resolved bytecode. 显然,它比执行已经解析的字节码需要更多的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.