Java循环效率

13

我正在比较Java中嵌套for、while和do-while循环的效率,并且我发现了一些奇怪的结果,需要帮助理解。

public class Loops {
    public static void main(String[] args) {
        int L = 100000;    // number of iterations per loop
        // for loop
        double start = System.currentTimeMillis();
        long s1 = 0;
        for (int i=0; i < L; i++) {
            for (int j = 0; j < L; j++) {
                s1 += 1;
            }
        }
        double end = System.currentTimeMillis();
        String result1 = String.format("for loop: %.5f", (end-start) / 1000);
        System.out.println(s1);
        System.out.println(result1);

        // do-while loop
        double start1 = System.currentTimeMillis();
        int i = 0;
        long s2 = 0;
        do {
            i++;
            int j = 0;
            do {
                s2 += 1;
                j++;
            } while (j < L);
        } while (i < L);
        double end1 = System.currentTimeMillis();
        String result2 = String.format("do-while: %.5f", (end1-start1) / 1000);
        System.out.println(s2);
        System.out.println(result2);

        // while loop
        double start2 = System.currentTimeMillis();
        i = 0;
        long s3 = 0;
        while (i < L) {
            i++;
            int j = 0;
            while (j < L) {
                s3 += 1;
                j++;
            }
        }
        double end2 = System.currentTimeMillis();
        String result3 = String.format("while: %.5f", (end2-start2) / 1000);
        System.out.println(s3);
        System.out.println(result3);
    }
}

所有循环的计数器总和为100亿;结果让我感到困惑:

for循环:6.48300

do-while循环:0.41200

while循环:9.71500

为什么do-while循环如此快?这种性能差距与L的任何变化成比例。我已经独立运行这些循环,它们的表现相同。


1
我无法复现你的数字。对我来说,两个while循环的速度相同,而for循环略慢一些。 - Mysticial
5
无论如何,这并不是一个特别好的基准测试,因为编译器或JIT可能能够完全删除内部循环。 - Mysticial
1
那一定是这样的情况 - 某种只在do-while循环中执行的优化。不过,我很想了解更多关于这个机制的信息。 - JohnF
是的,我不太确定这里发生了什么。我更擅长C和C++,而且几乎没有深入研究JVM/JIT的经验。 - Mysticial
1个回答

25

我已经运行了您提供的代码,并且惊讶地发现了性能差异。出于好奇心,我开始调查,发现尽管这些循环看起来在做同样的事情,但它们之间确实存在一些重要的区别。

第一次运行这些循环后,我的结果是:

for loop: 1.43100
do-while: 0.51300
while: 1.54500

但是当我运行这三个循环至少10次时,每个循环的性能基本相同。

for loop: 0.43200
do-while: 0.46100
while: 0.42900

JIT可以随着时间的推移来优化这些循环,但必须存在某些不同之处导致这些循环具有不同的初始性能。实际上有两个区别:
- do-while循环执行的比for和while循环更少的比较 - 为简单起见,假设L = 1
long s1 = 0;
for (int i=0; i < L; i++) {
    for (int j = 0; j < L; j++) {
        s1 += 1;

外循环:0 < 1
内循环:0 < 1
内循环:1 < 1
外循环:1 < 1

总共4次比较

int i = 0;
long s2 = 0;
do {
    i++;
    int j = 0;
    do {
        s2 += 1;
        j++;
    } while (j < L);
} while (i < L);

内部循环:1 < 1
外部循环:1 < 1

总共2次比较

  • 生成的字节码不同

为了进一步调查,我稍微修改了您的类,但不影响其工作方式。

public class Loops {
    final static int L = 100000; // number of iterations per loop

    public static void main(String[] args) {
        int round = 10;
        while (round-- > 0) {
            forLoop();
            doWhileLoop();
            whileLoop();
        }
    }

    private static long whileLoop() {
        int i = 0;
        long s3 = 0;
        while (i++ < L) {
            int j = 0;
            while (j++ < L) {
                s3 += 1;
            }
        }
        return s3;
    }

    private static long doWhileLoop() {
        int i = 0;
        long s2 = 0;
        do {
            int j = 0;
            do {
                s2 += 1;
            } while (++j < L);
        } while (++i < L);
        return s2;
    }

    private static long forLoop() {
        long s1 = 0;
        for (int i = 0; i < L; i++) {
            for (int j = 0; j < L; j++) {
                s1 += 1;
            }
        }
        return s1;
    }
}

然后编译它并调用 javap -c -s -private -l Loop 来获取字节码。
首先是 doWhileLoop 的字节码。
   0:   iconst_0        // push the int value 0 onto the stack
   1:   istore_1        // store int value into variable 1 (i)
   2:   lconst_0        // push the long 0 onto the stack
   3:   lstore_2        // store a long value in a local variable 2 (s2)
   4:   iconst_0        // push the int value 0 onto the stack
   5:   istore  4   // store int value into variable 4 (j)
   7:   lload_2     // load a long value from a local variable 2 (i)
   8:   lconst_1        // push the long 1 onto the stack
   9:   ladd        // add two longs
   10:  lstore_2        // store a long value in a local variable 2 (i)
   11:  iinc    4, 1    // increment local variable 4 (j) by signed byte 1
   14:  iload   4   // load an int value from a local variable 4 (j)
   16:  iload_0     // load an int value from a local variable 0 (L)
   17:  if_icmplt   7   // if value1 is less than value2, branch to instruction at 7
   20:  iinc    1, 1    // increment local variable 1 (i) by signed byte 1
   23:  iload_1     // load an int value from a local variable 1 (i)
   24:  iload_0     // load an int value from a local variable 0 (L)
   25:  if_icmplt   4   // if value1 is less than value2, branch to instruction at 4
   28:  lload_2     // load a long value from a local variable 2 (s2)
   29:  lreturn     // return a long value

现在 whileLooP 的字节码:
   0:   iconst_0        // push int value 0 onto the stack
   1:   istore_1        // store int value into variable 1 (i)
   2:   lconst_0        // push the long 0 onto the stack
   3:   lstore_2        // store a long value in a local variable 2 (s3)
   4:   goto        26
   7:   iconst_0        // push the int value 0 onto the stack
   8:   istore  4   // store int value into variable 4 (j)
   10:  goto        17
   13:  lload_2     // load a long value from a local variable 2 (s3)
   14:  lconst_1        // push the long 1 onto the stack
   15:  ladd        // add two longs
   16:  lstore_2        // store a long value in a local variable 2 (s3)
   17:  iload   4   // load an int value from a local variable 4 (j)
   19:  iinc    4, 1    // increment local variable 4 (j) by signed byte 1
   22:  iload_0     // load an int value from a local variable 0 (L)
   23:  if_icmplt   13  // if value1 is less than value2, branch to instruction at 13
   26:  iload_1     // load an int value from a local variable 1 (i)
   27:  iinc    1, 1    // increment local variable 1 by signed byte 1
   30:  iload_0     // load an int value from a local variable 0 (L)
   31:  if_icmplt   7   // if value1 is less than value2, branch to instruction at 7
   34:  lload_2     // load a long value from a local variable 2 (s3)
   35:  lreturn     // return a long value

为了使输出更易读,我附加了注释,根据Java bytecode instruction listings描述每个指令的作用。
如果您仔细观察,您会发现这两个字节码之间有一个重要的区别。while循环(for循环同样适用)在字节码末尾定义了if语句(if_icmplt指令)。这意味着为了检查第一个循环的退出条件,必须调用到第26行的goto,并且类似地,对于第二个循环,需要调用到第17行的goto。
以上字节码是在Mac OS X上使用javac 1.6.0_45生成的。
总结
我认为比较次数不同以及while和for循环字节码中存在goto指令是造成这些循环性能差异的原因。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接