FOR loop performance in PHP

The first way is slower because the count() function has to be called in every iteration of the loop. The count() method itself is pretty fast, but there is still some overhead in calling the function at all. By moving it outside the loop, you’re performing what is called “loop invariant code motion“, or sometimes “hoisting”.

There’s a whole family of optimizations like this that are interesting to learn about.

Having said all that, it seldom pays to stress about this very much. In your example here, the I/O of echoing the output is probably 10 times what you save through your “optimization”. And if you do anything else at all inside your loop, your optimization means less and less.

I hate to be a wet blanket, but for more than 90% of your code, performance is a non-issue. Especially when you talk about web applications, which are more than 90% I/O to begin with.

Still, when you think your code is to blame, you should:

  1. Decide on the use case you need to optimize
  2. Measure your code performance
  3. Find the bottlenecks
  4. Identify the areas you can improve and decide whether it is worth your time to improve them.
  5. Make your code changes
  6. Go back to step 2

You’ll nearly always discover that you need to improve your caching strategies and database optimization (which is just I/O optimization by another means), instead of twiddling code.

Leave a Comment