Which loop is faster, while or for?

后端 未结 16 2109
我寻月下人不归
我寻月下人不归 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:28

    Depends on the language and most likely its compiler, but they should be equivalent in most languages.

    0 讨论(0)
  • 2020-11-27 07:31

    As others have said, any compiler worth its salt will generate practically identical code. Any difference in performance is negligible - you are micro-optimizing.

    The real question is, what is more readable? And that's the for loop (at least IMHO).

    0 讨论(0)
  • 2020-11-27 07:33

    It shouldn't matter which is faster. If it does matter then benchmark it using your real code and see for yourself.

    The answers to this other question might be useful as well: How to write more efficient code

    0 讨论(0)
  • 2020-11-27 07:36

    Some optimizing compilers will be able to do better loop unrolling with a for loop, but odds are that if you're doing something that can be unrolled, a compiler smart enough to unroll it is probably also smart enough to interpret the loop condition of your while loop as something it can unroll as well.

    0 讨论(0)
提交回复
热议问题