Optimising for-loops
Posted by Tim Koschützki, on Apr 19, 2007 - in PHP & CakePHP » Performance, Optimization & Caching
For-loops and how not to use them
The following tip is another one that could greatly increase your script's performance. The thing is quite simple, so let's look at a code example:
This code is perfectly straightforward. It creates an array with the values ranging from 1 to 1000, keys from 0 to 999. Now the for-loop iterates over the array and echoes the array's values.
The problem with this code is that whenever the for-loop is executed, the count() function re-calculates the amount of entries in the array. For an array with only 1000 values this is not so much of a significant performance issue. Imagine, however, an array with 100 000 values! It could slow down your application a great deal!
Common sense to the rescue
The solution is pretty simple. Just calculate the length of the array before the for-loop:
What is the actual performance difference?
Let's try to measure the actual difference it all makes. For this we assign the array's values in the two loops to a variable called $b - not to cheat the script, but to make the output it los more simple, not having to scroll your browser window down to the actual time difference we need. :) Also to show a real difference, let's use an array of 100 000 values:
-
-
for($i=0;$i<count ($arr);$i++) {
-
$b = $arr[$i].'
-
';
-
}
-
';
-
-
-
for($i=0;$i< $length;$i++) {
-
$b = $arr[$i].'
-
';
-
}
-
';
The script's output speaks for itself:
0.139598846436
0.0997688770294
The first script part that has the count() function within the for-loop runs 0.04 seconds slower. Now imagine using the wrong approach in a large application with many loops, many calculations and more complex calculations within the loops.
Calculating the length of an array outside the loop is common sense and a best php coding practice.
Happy coding all!
5 Comments
Good stuff Mgcci. Will write a post about your comment definately!
[...] Temp in connection with loops as this can sometimes cause disastrious performance issues. Check Optimising Loops for further information about [...]
I recommend looking at this link
http://home.earthlink.net/~kendrasg/info/js_opt/jsOptMain.html
one of my favorite loops is the modified duff device..
=E
haha, nice link, Eric. Thanks. :]



Some tips to make it even faster
++$i is faster than $i++, you might want to consider that..
even faster?
you can try while loop...
even faster?
try --$length, loop the array the other way, so you don't even need to declare a new variable...