Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which loop is faster, while or for?

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?

like image 347
Mark Lalor Avatar asked Sep 02 '10 16:09

Mark Lalor


People also ask

Which loop is the fastest loop?

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.

Which loop is faster for or while in Python?

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.

Which is faster while or for loop Java?

The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all.

Which loop is faster in C for while or do-while?

"Do-While loop is the fastest loop in C programming".


1 Answers

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

like image 99
mmx Avatar answered Oct 27 '22 07:10

mmx