在Java中编译循环 [英] Compiling loops in Java
问题描述
我可以从 JVM中看到规范这段代码:
void spin() {
int i;
for (i = 0; i < 100; i++) {
; // Loop body is empty
}
}
应编译成:
0 iconst_0
1 istore_1
2 goto 8
5 iinc 1 1
8 iload_1
9 bipush 100
11 if_icmplt 5
14 return
其中条件检查 if_icmplt
是循环体之后,但当我自己编译和查看与javap,我看到:
where condition check if_icmplt
is after the loop body, but when I compile it myself and view with javap, I see:
0: iconst_0
1: istore_1
2: iload_1
3: bipush 100
5: if_icmpge 14
8: iinc 1, 1
11: goto 2
14: return
循环条件在循环体之前。为什么会发生这种情况?
and loop condition is before the cycle body. Why does this happen?
在身体之后放置条件阻止我们在每个循环后执行goto,并且对我看起来符合逻辑。那么为什么OracleJDK做另一种方式?
Placing condition after body prevents us from doing goto after every cycle and looks logical to me. So why is OracleJDK doing another way?
推荐答案
这不是为了更好的JIT优化 - 对于JIT,这些代码片段是等价的。这是因为没有意义在javac中进行优化,因为JIT优化无论如何都是更强大的。
It is not for better JIT optimizations - for JIT, these code snippets are equivalent. It is because there is no sense to make optimizations in javac, since JIT optimizations are more powerful anyway.
这篇关于在Java中编译循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!