Thursday, April 21, 2011

Counting in loops is bad, m'kay...

So you're working in php, and need to loop over something. While there are many ways to do this using loops such as...

do{
    // do stuff
}while( $x < 10 )

while( $x >= 4 )
{
    // do stuff
}

foreach( $array as $key => $value )
{
    // do stuff
}

for( $i = 0; $i < count( $array ); $i++ )
{
    // do stuff
}

...there are some things you should keep in mind. One of the more common mistakes people make when using loops, is placing unnecessary processes in your loop, such as count().

for( $i = 0; $i < count( $array ); $i++ )
{
// do stuff
}

The problem with using count() in your loops is pretty obvious when you think about it. For each loop, the interpreter has to make these steps:
1) Evaluate your conditional...

$i < count( $array )

2) ...but when the interpreter gets to count( $array ), it has to stop to evaluate because it doesn't know how to compare the integer represented by $i with the function count()...

count( $array ) 

3) ...so that it can make an actual comparison. This way, the interpreter is no longer comparing...

$i < count( $array )

...but rather two integers such as...

1 < 5

So what do we do to fix this? Simple, abstract the count function outside of the loop like so:

$count = count( $array );
for( $i = 0; $i < $count; $i++ )
{
   // do stuff
}

Now that count() is abstracted out of the loop, the interpreter is now able to change...

$i < $count

...in one step, to this...

1 < 5

So what's the point of changing this? Try as much as a 300% speed difference! Don't believe me? Try the code yourself.