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:

php
  1. $arr = range(1,1000);
  2.  
  3. for($i=0;$i<count($arr);$i++) {
  4.       echo $arr[$i].'
  5. ';
  6. }

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:

php
  1. $arr = range(1,1000);
  2. $length = count($arr);
  3.  
  4. for($i=0;$i<$length;$i++) {
  5.       echo $arr[$i].'
  6. ';
  7. }

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:

php
  1. $start = array_sum(explode(' ',microtime()));
  2. $arr = range(1,100000);
  3.  
  4. for($i=0;$i<count ($arr);$i++) {
  5.       $b = $arr[$i].'
  6. ';
  7. }
  8. $end = array_sum(explode(' ',microtime()));
  9. echo ($end - $start).'
  10. ';
  11.  
  12. $start = array_sum(explode(' ',microtime()));
  13. $arr = range(1,100000);
  14. $length = count($arr);
  15.  
  16. for($i=0;$i< $length;$i++) {
  17.       $b = $arr[$i].'
  18. ';
  19. }
  20. $end = array_sum(explode(' ',microtime()));
  21. echo ($end - $start).'
  22. ';

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!