

For example, consider the following code: The second "must avoid" loop problem is loop-invariant code, which is the practice of calculating things inside a loop that could be done, all or in part, outside the loop.

On my test computer using count() in the loop took eight seconds and not using count in the loop took four seconds - quite a substantial difference, but it was on an array of 3,000,000 items! There are a number of ways you can speed up loop execution, of which two are the most common: calling a function as part of the loop condition, and loop-invariant code.
#FOREACH PHP OPTMIZE CODE#
One of the best places to look for optimisation opportunities is in loops, as they clearly embody code that needs to be executed multiple times. Granted, from a purely programmatic point of view it is never a bad thing to optimise even rarely used code, however few people and even fewer companies have the time to spend optimising everything, so you should generally try to focus your efforts on what will give the greatest return. Granted that is a vast over-generalisation and it is probably not very true, either, however the principle is correct: you can spend hours and hours optimising your program randomly and find it runs no faster because you have been optimising bits that are not run very often. A good rule of thumb to keep in mind is "90% of your scripts execution time is taken up in 10% of the code".
