Is there any difference between an infinite loop with for and while?

6

In PHP, you can generate an infinite loop with while simply by passing the true parameter.

Example:

while (true) {
      echo "Ao infinito e além";
}

It is also possible to generate this through for , simply omitting the parameters, passing the ; .

Example:

 for(;;) {
   echo "Não lembro o desenho que usa a frase acima";
 }

Is there any functional difference between the two?

Does the performance change?

Is there any advantage and disadvantage between one and another?

    
asked by anonymous 01.10.2015 / 22:55

2 answers

7

I'll answer the obvious. It does not change anything. It's like.

From a performance standpoint the AP already knows, it does not matter.

But if you want to know if there is a minimal difference, it looks like it was in older versions, as analyzed by ircmaxell in its great answer in SO .

Changed in version 5.5 and remained the same. It may change again in the future, although I doubt it.

Most languages produce identical codes. It has language that prefers the use of for by generating a warning for while by taking advantage of which syntax you should use. for in this way is unambiguously an loop infinity. With while may have happened unintentionally. It's quite true that many times the compiler identifies that there is a while(true) after optimizations made and it was not written exactly this.

Related: Difference between while and for and How to transform a while structure into for? And vice versa?

    
01.10.2015 / 23:17
4

Is there any functional difference between the two?

No. The only difference is in the design of the function, some like to use for other while because the code is clearer and readable.

Changes performance?

No.

According to the PHPBENCH it is possible to analyze the benchmark between the use of the two loops:

%for($i = 0; $i < 1000000; ++$i); Total time: 16558 µs

$i = 0; while($i < 1000000) ++$i; Total time: 16855 µs

Is there any advantage and disadvantage between one and another?

No.

It's the developer's liking, even though the current use of while is more constant because of the design and makes the code more readable.

    
01.10.2015 / 23:36