Monday, August 24, 2009

Optimize your code: Keep functions out of statements!

It's always said that we should think out of the box. In any programming language, we should write functions out of certain statements statements.

Consider this:
<?php

$arr = array(/* 10000 elements */);
for($i = 0; $i < count($arr); $i++){
// ...
}

?>


If you work this out slowly using a debugger or what, you would have noticed that count($arr) will be called for each iteration of the for loop! Each time you call count($arr), count() actually works out your array size and if your array is huge, the script will be stuck at this loop for a few seconds.

So what about doing something like this?
<?php

$arr = array(/* 10000 elements */);
$l = count($arr);
for($i = 0; $i < $l; $i++){
// ...
}

?>

Isn't this logically cleaner and faster in execution?

This also applies to while loop.

No comments: