Speeding up PHP FOR loops


Refactoring some client code the other day I found a lot of inefficient logic. Whilst this example is written in PHP the concept is applicable in other programming languages.

Many people use for loops in the belief that they are faster than a foreach, and while this is often the case it can be slower and less flexible if you make some simple mistakes. Consider the following:

A slow FOR loop

$text="thequickbrownfoxjumpsoverthelazydog";
for($i=0; $i < strlen($text); $i++){ // Loop through the characters
echo ( substr($text,$i,1) == 'o' ) ? "Its an o" : "Not an o"; // Display true or false as relevant
}

A faster FOR loop

$text="thequickbrownfoxjumpsoverthelazydog";
$length = strlen($text); // obtain length of the string
for($i=0; $i < $length ; $i++){ // Loop through the characters
echo ( substr($text,$i,1) == 'o' ) ? "Its an o" : "Not an o"; // Display true or false as relevant
}

The second loop is faster because it does not evaluate the string length each time the loop runs strlen($text) as in the first example. Small differences like this can have a large effect on the speed of scripts especially if there are many loops or iterations.