views:

243

answers:

4

What are the performance issue of using while loop v/s foreach/for loop or vice-versa ?

Also is it always preferable to use foreach loop v/s while in php ?

+5  A: 

You've listed this as "language-agnostic," but the answer will be language (or, rather, compiler)-specific.

Theoretically, foreach can be just as fast, if not faster, especially if the regular for loop keeps doing an expensive operation to test the Count.

Also, foreach works for a lazy-loaded collection, a regular for loop must know the number of item ahead of time.

Finally, even if foreach is slightly slower on your platform, it is highly unlikely the difference will matter, and it is much more maintainable than a for loop. Don't prematurely optimize. (This was, incidentally, the case for .NET for while, they've since tidied up the performance of enumerators.)

richardtallent
a `for` loop doesn't need to know the size ahead of time
warren
@warren: a C-style `for` loop you mean. That's why language-agnostic doesn't help at all here.
Martinho Fernandes
many styles of for loop don't need to know - and everyone i've ever seen can be broken-out-of in some fashion, so making it flexible isn't too hard normally
warren
+2  A: 

Hypothetically, a foreach may be slower - a for loop and a while loop with the same condition should be equivalent.

foreach needs to go through the data structure at hand, so whatever the structure's lookup for next (and maintaining state) may slow you down.

However, if you're doing that manually in a for or while loop, then it's probably the same.

The best answer, of course, is try it and time it and see what the answer actually is.

warren
A: 

Short answer: no. It's not a useful thing to waste even a single thought on.

Michael Borgwardt
A: 

I wrote an article for php|architect on the very issue of looping in PHP. Basically, benchmarks show, that there's no significant impact from the looping overhead... even when using my lazy numeric range extension.

IIRC, foreach is 2.9x slower than a for loop, once you exclude memory and the costs of generator functions. If the contents of your loop are less than 2.9x of the loop overhead, then you might want to reconsider what you're doing.

Furthermore, if you're seeking raw loop performance in a language, PHP should be on your list of absolute last choices. It's interpreted and, separately, not well suited for long-running operations.

Most PHP coders waste innumerable cycles concatenating strings. This speaks to the premature optimization warnings. I bet I can double your performance simply by adding commas to your "echo" statements.

Profile your code with XDebug or something. Find your real bottlenecks. Looping isn't it. Trust me. It never is.

Pestilence