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

Asked

Viewed 260 times

7

In PHP, it is possible to generate a loop infinity with while simply passing the parameter true.

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?

Change the performance?

Is there some advantage and disadvantage between one and the other?

  • I believe that because they are infinite loops, both are equal in terms of performance, but let’s wait for someone with more knowledge about...

2 answers

11


I’ll answer the obvious: it doesn’t change anything, it’s taste.

From a performance point of view AP already knows, no matter.

But if you want to know if there is a minimum difference, it seems that had in old versions, as analysis made by ircmaxell in its great response in the OS.

It changed in version 5.5 and became identical. It can change again in the future, although I doubt.

Most languages produce identical codes in this case. It has language that prefers the use of for generating a Warning to the while taking advantage of which syntax you should use. The for in this way is unequivocally a loop infinite. With the while may have happened unintentionally. It is true that often 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?

6

Is there any functional difference between the two?

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

Change the performance?

Not.

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 some advantage and disadvantage between one and the other?

Not.

It is by taste of the developer, even if currently using while be more constant because of the design and makes the code more readable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.