如果您不运行预热阶段,则第一个循环可能会得到优化和编译,而第二个循环则不会,而当您合并它们时,整个合并的循环都会被编译。此外,使用该server选项和您的代码,大多数都得到优化,因为您不使用结果。
我已经运行了下面的测试,将每个循环以及合并的循环放在它们自己的方法中,并预热 JVM 以确保一切都被编译。
结果(JVM 选项:)-server -XX:+PrintCompilation:
- 循环 1 = 500 毫秒
 
- 循环 2 = 900 毫秒
 
- 合并循环 = 1,300 毫秒
 
所以合并循环稍微快一点,但没那么快。
public static void main(String[] args) throws InterruptedException {
    for (int i = 0; i < 3; i++) {
        loop1();
        loop2();
        loopBoth();
    }
    long start = System.nanoTime();
    loop1();
    long end = System.nanoTime();
    System.out.println((end - start) / 1000000);
    start = System.nanoTime();
    loop2();
    end = System.nanoTime();
    System.out.println((end - start) / 1000000);
    start = System.nanoTime();
    loopBoth();
    end = System.nanoTime();
    System.out.println((end - start) / 1000000);
}
public static void loop1() {
    int a = 188, aMax = 0;
    for (int i = 0; i < 1000000000; i++) {
        int t = a ^ i;
        if (t > aMax) {
            aMax = t;
        }
    }
    System.out.println(aMax);
}
public static void loop2() {
    int b = 144, bMax = 0;
    for (int i = 0; i < 1000000000; i++) {
        int t = b ^ i;
        if (t > bMax) {
            bMax = t;
        }
    }
    System.out.println(bMax);
}
public static void loopBoth() {
    int a = 188, b = 144, aMax = 0, bMax = 0;
    for (int i = 0; i < 1000000000; i++) {
        int t = a ^ i;
        if (t > aMax) {
            aMax = t;
        }
        int u = b ^ i;
        if (u > bMax) {
            bMax = u;
        }
    }
    System.out.println(aMax);
    System.out.println(bMax);
}