Java:for(;;) 与 while(true) [英] Java: for(;;) vs. while(true)
问题描述
标准的 while(true)
循环和 for(;;)
有什么区别?
What is the difference between a standard while(true)
loop and for(;;)
?
有没有,或者编译后都会映射到同一个字节码?
Is there any, or will both be mapped to the same bytecode after compiling?
推荐答案
在语义上,它们是完全等效的.这是一个品味问题,但我认为 while(true)
看起来更干净,并且乍一看更容易阅读和理解.在 Java 中,它们都不会导致编译器警告.
Semantically, they're completely equivalent. It's a matter of taste, but I think while(true)
looks cleaner, and is easier to read and understand at first glance. In Java neither of them causes compiler warnings.
在字节码级别,可能取决于编译器和优化级别,但原则上发出的代码应该是相同的.
At the bytecode level, it might depend on the compiler and the level of optimizations, but in principle the code emitted should be the same.
在我的编译器上,使用 Bytecode Outline 插件,for(;;){}
看起来像这样:
On my compiler, using the Bytecode Outline plugin,the bytecode for for(;;){}
looks like this:
L0
LINENUMBER 6 L0
FRAME SAME
GOTO L0
while(true){}
的字节码如下所示:
L0
LINENUMBER 6 L0
FRAME SAME
GOTO L0
所以是的,至少对我来说,它们是相同的.
So yes, at least for me, they're identical.
这篇关于Java:for(;;) 与 while(true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!