Thursday, April 9, 2009

PHP for loop optimization

The for loop is a staple of just about every programming language including php. Here is the basic structure:
for (expr1; expr2; expr3)
statement(s)

expr1 is evaluated at the beginning of the loop. expr2 is evaluated at the beginning of each iteration and if true the loop continues and statement(s) is executed. expr3 is executed at the end of each iteration. The following is a common practice when using a for loop to iterate through an array:
for ($i = 0 ; $i < count($array) ; $i++) {
//statements here
}

This works but is not optimized because the count($array) function must be executed on every iteration. It would be better to evaluate this and store it in a variable prior to executing the loop as follows:
$count = count($array);
for ($i = 0 ; $i < $count ; $i++) {
//statements here
}

What is often overlooked regarding for loops is that each of the expressions can be empty or contain multiple expressions separated by commas. So we could also write the previous example as:
for ($i = 0, $count = count($array) ; $i < $count ; $i++) {
//statements here
}

No comments:

Post a Comment