Which loop is faster, while or for?

Mark Lalor picture Mark Lalor · Sep 2, 2010 · Viewed 110.3k times · Source

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?

Answer

Mehrdad Afshari picture Mehrdad Afshari · Sep 2, 2010

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