Java效率

x4-*_*x4- 12 java performance

我正在使用一些代码来计算计算某些Java代码所需的时间,以了解Java某些功能的效率或低效率.这样做我现在陷入了一些非常奇怪的效果,我无法解释自己.也许你们中的某个人可以帮助我理解它.

public class PerformanceCheck {

 public static void main(String[] args) {
    List<PerformanceCheck> removeList = new LinkedList<PerformanceCheck>();

    int maxTimes = 1000000000;

    for (int i=0;i<10;i++) {
        long time = System.currentTimeMillis();

        for (int times=0;times<maxTimes;times++) {
            // PERFORMANCE CHECK BLOCK START

            if (removeList.size() > 0) {
                testFunc(3);
            }

            // PERFORMANCE CHECK BLOCK END
        }

        long timeNow = System.currentTimeMillis();
        System.out.println("time: " + (timeNow - time));
    }
 }

 private static boolean testFunc(int test) {
    return 5 > test;
 }

}
Run Code Online (Sandbox Code Playgroud)

启动这会导致相对较长的计算时间(请记住removeList为空,因此甚至不调用testFunc):

time: 2328
time: 2223
...
Run Code Online (Sandbox Code Playgroud)

虽然将removeList.size()> 0和testFunc(3)的任何组合替换为其他任何东西都有更好的结果.例如:

...
if (removeList.size() == 0) {
    testFunc(3);
}
...
Run Code Online (Sandbox Code Playgroud)

结果(每次调用testFunc):

time: 8
time: 7
time: 0
time: 0
Run Code Online (Sandbox Code Playgroud)

即使调用两个函数彼此独立也会导致计算时间缩短:

...
if (removeList.size() == 0);
    testFunc(3);
...
Run Code Online (Sandbox Code Playgroud)

结果:

time: 6
time: 5
time: 0
time: 0
...
Run Code Online (Sandbox Code Playgroud)

在我的初始示例中,只有这种特殊组合需要很长时间.这让我感到恼火,我真的很想理解它.这有什么特别之处?

谢谢.

加成:

在第一个示例中更改testFunc()

if (removeList.size() > 0) {
                testFunc(times);
}
Run Code Online (Sandbox Code Playgroud)

等等

private static int testFunc2(int test) {
    return 5*test;
}
Run Code Online (Sandbox Code Playgroud)

会导致再次快速.

use*_*300 0

这些基准测试非常严格,因为编译器非常智能。一种猜测:由于 testFunc() 的结果被忽略,编译器可能会完全优化它。添加一个计数器,比如

   if (testFunc(3))
     counter++;
Run Code Online (Sandbox Code Playgroud)

并且,为了彻底起见,请System.out.println(counter)在最后执行 a 。

  • 可能是顺序,正如 @prelic 所建议的。由于某种原因,JIT 第一次没有优化掉该调用,但第二次就解决了。 (2认同)