You can get the same output with for and while loops:
While:
$i = 0; while ($i <= 10){ print $i."\n"; $i++; };
For:
for ($i = 0; $i <= 10; $i++){ print $i."\n"; }
But which one is faster?
For loop (forward and reverse) The traditional for loop is the fastest, so you should always use that right? Not so fast - performance is not the only thing that matters. Code Readability is usually more important, so default to the style that fits your application.
In this case, the for loop is faster, but also more elegant compared to while. Please, have in mind that you can't apply list comprehensions in all cases when you need loops. Some more complex situations require the ordinary for or even while loops.
The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all.
"Do-While loop is the fastest loop in C programming".
That clearly depends on the particular implementation of the interpreter/compiler of the specific language.
That said, theoretically, any sane implementation is likely to be able to implement one in terms of the other if it was faster so the difference should be negligible at most.
Of course, I assumed while
and for
behave as they do in C and similar languages. You could create a language with completely different semantics for while
and for
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With