while(true) vs for(;;)
2016-08-15 本文已影响0人
williamlee
while(true)和for(;;)到底谁快?
test code
public class TestLoop {
public void whileCode(){
while (true){ }
}
public void forCode(){
for (;;){ }
}
}
字节码
执行命令: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 */
根据生成的字节码在java
中两者没有区别。分别在两个循环中累加到1,000,000,000, 花费时间分别为2毫秒代码不粘贴出来了。结论不敢乱下,但是个人认为两者并没区别。