美文网首页
while(true) vs for(;;)

while(true) vs for(;;)

作者: williamlee | 来源:发表于2016-08-15 22:24 被阅读0次

    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毫秒代码不粘贴出来了。结论不敢乱下,但是个人认为两者并没区别。

    相关文章

      网友评论

          本文标题:while(true) vs for(;;)

          本文链接:https://www.haomeiwen.com/subject/xaausttx.html