前言
在Java中 for(;;)和while(true)都是死循环,使用的效果都是一样的,但是我们都知道Java是使用编译后的字节码来运行的,下面来看看这两个命令编译后的效果:
for(;;)
public void test(){
for(;;){
System.out.println("for"+"+++");
}
}
编译后字节码为:
public void test();
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String for+++
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: goto 0
LineNumberTable:
line 18: 0
LocalVariableTable:
Start Length Slot Name Signature
0 11 0 this Lcom/jj/jingcai/MyTest;
StackMapTable: number_of_entries = 1
frame_type = 0 /* same */
RuntimeVisibleAnnotations:
0: #17()
while(true)
public void test(){
while (true){
System.out.println("while"+"---");
}
}
编译后字节码为:
public void test();
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String while---
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: goto 0
LineNumberTable:
line 18: 0
LocalVariableTable:
Start Length Slot Name Signature
0 11 0 this Lcom/jj/jingcai/MyTest;
StackMapTable: number_of_entries = 1
frame_type = 0 /* same */
RuntimeVisibleAnnotations:
0: #17()
总结:两者编译后的字节码竟然惊人的一致,But注意 这是 依赖于编译器优化后的结果。--->有些不优化的编译器-->则会体现出不同。for(;;)的指令就会少一些。而while(true)会用到寄存器,就会多一些指令。虽然不大,但是强迫症还是会选for(;;)的吧哈哈!

网友评论