debuggable

Optimising for-loops

Posted on 19/4/07 by Tim Koschützki 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:

\$arr = range(1,1000);

for(\$i=0;\$i<count(\$arr);\$i++) {
echo \$arr[\$i].'
'
;
}

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:

\$arr = range(1,1000);
\$length = count(\$arr);

for(\$i=0;\$i<\$length;\$i++) {
echo \$arr[\$i].'
'
;
}

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:

\$start = array_sum(explode(' ',microtime()));
\$arr = range(1,100000);

for(\$i=0;\$i<count (\$arr);\$i++) {
\$b = \$arr[\$i].'
'
;
}
\$end = array_sum(explode(' ',microtime()));
echo (\$end - \$start).'
'
;

\$start = array_sum(explode(' ',microtime()));
\$arr = range(1,100000);
\$length = count(\$arr);

for(\$i=0;\$i< \$length;\$i++) {
\$b = \$arr[\$i].'
'
;
}
\$end = array_sum(explode(' ',microtime()));
echo (\$end - \$start).'
'
;

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! 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...

[...] 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