Last week I wrote about some optimizations you can apply to your code that will improve the performance of your site significantly. I also mentioned that regularly an article pops up talking about ways to shave time off your scripts, and I talked about how these articles mostly are bunk. Like this one.
The article I linked above is a run-of-the-mill micro optimization list. The difference here is that the author actually makes use of some benchmarks to make their point. So, let’s go step by step and discover together why this article takes longer to read than the amount of CPU time it saves.
Loops
The author asserts that it is best to calculate the maximum value for a for loop outside of the declaration of the loop. Inadvertently, the author stumbles upon a tried-and-true programming technique: don’t repeat yourself.
The code sample:
#Worst than foreach and while loop for($i =0; $i < count($array);$i++){ echo 'This is bad, my friend'; }
#Better than foreach and while loop $total = (int)count($array); for($i =0; $i < $total;$i++){ echo 'This is great, my friend'; }