首页 > 解决方案 > while 和 for 循环之间在计算上有什么区别吗?

问题描述

只是想知道之间是否有任何计算差异:

for(;condition;) {
    //task
}

while(condition) {
    //task
}

标签: javaloopsbig-o

解决方案


no difference这两种情况下都有Java compiler generates the same byte code。如果您在我使用时查看字节码for loop

  0: bipush        11
  2: istore_1
  3: goto          9
  6: iinc          1, -1
  9: iload_1
 10: bipush        10
 12: if_icmpgt     6
 15: return

上面的字节码为下面的代码生成:

    int a = 11;
    for (; a > 10;) {
        a--;
    }

和相同的字节码:

   Code:
      0: bipush        11
      2: istore_1
      3: goto          9
      6: iinc          1, -1
      9: iload_1
     10: bipush        10
     12: if_icmpgt     6
     15: return

我使用时编译器生成的while loop

    int a = 11;
    while (a > 10) {
        a--;
    }

推荐阅读