Search code examples
phpperformanceprogramming-languageslanguage-features

Are there performance issue of using while loop vs foreach/for loop?


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 ?


Solution

  • 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.)