on Mythbusters

PHP Mythbusters: Count inside for loop is slow

11 comments
code

This one should be easy. I am trying to determine if calculating the length of the loop in advance is faster then counting inside a for loop.

If we code straight, we should always avoid doing something big inside a for loop or any other kind of loop. For example, it is always better to write a more complex SQL query and get all that we need to show to the user before the loop and avoid making n SQL queries inside a loop.

Consider this two code snippets:

$a = array_fill(5, 1000, 'test');
for($i=0; $i<count($a);$i++) {
    ///some code
}

and

$a = array_fill(5, 1000, 'test');
$length = count($a);
for($i=0; $i<$length; $i++) {
    ///some code
}

In the first snippet, PHP has to calculate the length of the loop every time, so it is considerably slower then the second snippet.

So, this Myth is CONFIRMED and you should always count or sizeof the length of a loop before the loop and then use this value for the loop.

To get even more excellent content, you can follow me on Twitter.



11 Responses to “PHP Mythbusters: Count inside for loop is slow”

Trackbacks/Pingbacks