我在以下代码中遇到了(对我而言)奇怪的运行时行为:

public class Main{

    private final static long ROUNDS = 1000000;
    private final static double INITIAL_NUMBER = 0.45781929d;
    private final static double DIFFERENCE = 0.1250120303d;


    public static void main(String[] args){

        doSomething();
        doSomething();
        doSomething();
    }


    private static void doSomething(){

        long begin, end;
        double numberToConvert, difference;


        numberToConvert = INITIAL_NUMBER;
        difference = DIFFERENCE;

        begin = System.currentTimeMillis();

        for(long i=0; i<ROUNDS; i++){

            String s = "" + numberToConvert;

            if(i % 2 == 0){
                numberToConvert += difference;
            }
            else{
                numberToConvert -= difference;
            }
        }

        end = System.currentTimeMillis();

        System.out.println("String appending conversion took " + (end - begin) + "ms.");
    }
}


我希望程序每次都能打印出类似的运行时。但是,我得到的输出始终是这样的:

String appending conversion took 473ms.
String appending conversion took 362ms.
String appending conversion took 341ms.


第一次通话比之后的通话慢30%。在大多数情况下,第二个呼叫也比第三个呼叫要慢一些。

java / javac版本:

javac 1.7.0_09 java version "1.7.0_09" OpenJDK Runtime Environment (IcedTea7 2.3.3) (7u9-2.3.3-0ubuntu1~12.04.1) OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)


所以,我的问题是:为什么会这样?

最佳答案

即时(JIT)编译器正在动态分析您的代码并优化执行。一段代码执行得越频繁,它的优化效果就越好。

例如,请参阅此问题以获取更多信息:(How) does the Java JIT compiler optimize my code?

关于java - Java:main中奇怪的运行时行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13616200/

10-09 00:32