为什么test1()的运行速度比test2()快得多?

use*_*372 2 java profile performance

import java.util.Random;


public class Test{
    static int r = new Random().nextInt(2);
    static int a(){
        return r==1 ? 1 :0;
    }

    public static void test1() throws  Exception {
        //
        System.out.println(1403187139018L);
        for (int i = 0; i <   1073741824; i++) {}//*

        // Thread.sleep(20000);
        long d = 0;

        for (int j = 0; j < 10; j++) {
            long y = System.currentTimeMillis();

            for (int x = 0; x < 1073741823; x++) {
                d += r==0?1:0;
            }
            System.out.println((System.currentTimeMillis() -y));
        }
    }

    public static void test2()  throws  Exception{

        // Thread.sleep(20000);
        long d = 0;

        for (int j = 0; j < 10; j++) {
            long y = System.currentTimeMillis();

            for (int x = 0; x < 1073741824; x++) {
                d += r==0?1:0;
            }
            System.out.println((System.currentTimeMillis() -y));

            // System.out.println("time:"+ (System.currentTimeMillis() - y));
        }
    }

    public static void main(String[] args) throws  Exception{
        // Thread.sleep(20000);

        test1();
        test2();

    }

}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我得到了这个输出:

32
26
28
28
32
29
35
33
30
31
1321
1308
1324
1277
1348
1321
1337
1413
1287
1331
Run Code Online (Sandbox Code Playgroud)

为什么test1要快得多?

除以下情况外没有区别:

System.out.println(1403187139018L);
for (int i = 0; i <   1073741824; i++) {}//*
Run Code Online (Sandbox Code Playgroud)

此外,test1的时间成本是25-35毫秒,我觉得难以置信.我在C中编写了相同的代码,每个for循环运行大约需要4秒钟.

这种行为似乎很奇怪.我怎么知道何时添加:

System.out.println(1403187139018L);
for (int i = 0; i <   1073741824; i++) {}//*
Run Code Online (Sandbox Code Playgroud)

另外,如果我改变了

r==0?1:0
Run Code Online (Sandbox Code Playgroud)

a()
Run Code Online (Sandbox Code Playgroud)

然后test2()比test1()运行得更快.

我得到的输出是:

1403187139018
3726
3729
3619
3602
3797
4362
4498
3816
4143
4368
1673
1386
1388
1323
1296
1337
1294
1283
1235
1460
Run Code Online (Sandbox Code Playgroud)

原始遗留代码:...

long t = System.currentTimeMillis();
MappedByteBuffer mbb = map(new File("temp.mmp"), 1024L * 1024 * 1024);

System.out.println("load " + (System.currentTimeMillis() - t));//*
for (int i = 0; i < 2014L * 1024 * 1024; i++) {}//*
int d = 0;
for (int j = 0; j < 10; j++) {
    t = System.currentTimeMillis();
    mbb.position(0);
    mbb.limit(mbb.capacity());

    for (int i = 0; i < mbb.capacity(); i++) {
        d += mbb.get();
    }

    ....
}
System.out.println(d);
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

空循环可能在第一种方法中触发JIT编译.并且JIT足够聪明,可以意识到除了获取当前时间和打印时间差异之外,您的代码没有做任何有用的事情.所以它通过不运行它来优化无用的代码.

如果您编写实际有用的代码,JIT将做正确的事情.不要试图通过添加空循环来搞乱它.