在 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
where条件检查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?
在 body 之后放置条件可以防止我们在每个循环后都执行 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屋!