Monday, August 6, 2007

PHP: count($var) in loops

I can remember -- when I was in college -- someone mentioning that
for(i=0;i<array.length;i++)
was a bad idea, because you were calling the length function every time through the loop. The better way was to set a variable to the length and use that. I never saw any speed difference tho, so I just kinda skipped that step every time.

However, in a site I recently built, the menu was database driven and it seemed to be taking forever to load. I was going thru the code trying to optimize it and found some places in the PHP where I was using count($array) in loops. So, just for the fun of it, I changed my code to
for($i=0, $num=count($array);$i<$num;$i++)
and it fixed all the issues. Granted, I was probably looping between 3-400 times, but the change probably saved 3-4 seconds of render time. Pretty cool. So anyway, keep in mind that those little optimizing hints actually do work.