Which loop is faster, while or for?

后端 未结 16 2343
我寻月下人不归
我寻月下人不归 2020-11-27 07:07

You can get the same output with for and while loops:

While:

$i = 0;
while ($i <= 10){
  print $i.\"\\n\";
  $i++;
};
         


        
16条回答
  •  甜味超标
    2020-11-27 07:20

    Isn't a For Loop technically a Do While?

    E.g.

    for (int i = 0; i < length; ++i)
    {
       //Code Here.
    }
    

    would be...

    int i = 0;
    do 
    {
      //Code Here.
    } while (++i < length);
    

    I could be wrong though...

    Also when it comes to for loops. If you plan to only retrieve data and never modify data you should use a foreach. If you require the actual indexes for some reason you'll need to increment so you should use the regular for loop.

    for (Data d : data)
    {
           d.doSomething();
    }
    

    should be faster than...

    for (int i = 0; i < data.length; ++i)
    {
          data[i].doSomething();
    }
    

提交回复
热议问题