while(true)和for(;;)到底誰快?
test code
public class TestLoop {
public void whileCode(){
while (true){ }
}
public void forCode(){
for (;;){ }
}
}
字節(jié)碼
執(zhí)行命令:javap -verbose .\TestLoop.class
public void whileCode();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=0, locals=1, args_size=1
0: goto 0
LineNumberTable:
line 7: 0
LocalVariableTable:
Start Length Slot Name Signature
0 3 0 this LTestLoop;
StackMapTable: number_of_entries = 1
frame_type = 0 /* same */
public void forCode();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=0, locals=1, args_size=1
0: goto 0
LineNumberTable:
line 14: 0
LocalVariableTable:
Start Length Slot Name Signature
0 3 0 this LTestLoop;
StackMapTable: number_of_entries = 1
frame_type = 0 /* same */
根據(jù)生成的字節(jié)碼在java
中兩者沒有區(qū)別。分別在兩個循環(huán)中累加到1,000,000,000, 花費時間分別為2毫秒代碼不粘貼出來了嗦董。結(jié)論不敢亂下涵防,但是個人認(rèn)為兩者并沒區(qū)別铜幽。