只是想知道之间是否存在任何计算差异:
for(;condition;) {
//task
}
Run Code Online (Sandbox Code Playgroud)
和
while(condition) {
//task
}
Run Code Online (Sandbox Code Playgroud)
有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
Run Code Online (Sandbox Code Playgroud)
上面的字节码是为以下代码生成的:
int a = 11;
for (; a > 10;) {
a--;
}
Run Code Online (Sandbox Code Playgroud)
和相同的字节码:
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
Run Code Online (Sandbox Code Playgroud)
我使用时已由编译器生成 while loop
int a = 11;
while (a > 10) {
a--;
}
Run Code Online (Sandbox Code Playgroud)