PHP Mythbusters: Count inside for loop is slow

Nov 24, 2010 10 Comments by

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.

Mythbusters

About the author

I am a passionate web developer with more then 10 years experience in PHP and other web related technology. My main interest is backend side of the web, but was doing both sides.

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

  1. SF says:

    Length spellings don’t match in the second snippet.

    Other than that, it would be more clear if you demonstrated that count($a) is actually re-evaluated during each iteration in the first snippet. I would suggest doing so by adding or removing elements to the $a array inside of the loop, writing a function to use instead of count() that also prints whenever it gets called, or showing opcode like in the last post.

    I don’t doubt that what you’re saying is correct, I just don’t think you’ve done more than demonstrate why the “myth” exists.

  2. Sam P says:

    I see what you’re trying to say here, but to be honest these snippets aren’t a valid example of your point.
    The count($a) command executes so quickly that it is almost negligible – even up to extremely large array sizes.

    Try the following:

    <?php
    $a = array_fill(1, 10, 'Array_Contents');
    $length = count($a);
    echo"Start script”;

    $time_start = microtime(true);

    for($i=0; $i<count($a);$i++) {
    sleep(1);
    }
    $time_mid = microtime(true);

    for($i=0; $i<$length; $i++) {
    sleep(1);
    }
    $time_end = microtime(true);

    echo "First for loop:" . $time_mid – $time_start. " seconds”;
    echo “Second for loop: ” . $time_end – $time_mid. ” seconds”;

    ?>

    Also, line 3 on the second script has a typo for the $length variable. Good series though, keep up the good work.

  3. mario says:

    Well, Mr. Confirmed, it looks like you did a conclusion, not a benchmark. How much is the runtime difference? And which uses cases has a for loop over a foreach anyway, and when would you recommend this particular micro optimization?

    • Shayne says:

      I can’t help but agree. Might as well make a blog post titled “Spagetti is better than linguini” and the contents can be “spagetti is thinner thus better”. I’d like to see how this conclusion was reached.

    • Andreas Nurbo says:

      The point is not really the runtime difference in the use of count() the point is best practice. Don’t make timeconsuming function calls in the evaluation part of for and while loops if you can avoid it. It slows stuff down. I’ve seen people do it a lot of times.

      If you just want to traverse an array foreach works fine. Thats its usecase. for() loops can be used for a whole bunch of stuff.

  4. Chris says:

    You tell us it’s confirmed but don’t offer any benchmarking. Some time back I had a look and benchmarked it. Results here: http://www.electrictoolbox.com/php-for-loop-counting-array/

    • Sam P says:

      That was kind of my benchmarking results also. Definitely a difference, but measured in microseconds, – even with a very large count.

      It all helps though I guess…

  5. huarong says:

    <?PHP
    $s1 = microtime(true);
    $a = array_fill(5, 100000, 'test');
    for($i=0; $i<count($a);$i++) {
    ///some code
    }

    $s2 = microtime(true);

    print ($s2-$s1).PHP_EOL;

    $a = array();
    $a = array_fill(5, 100000, 'tAst');
    $count = count($a);
    for($i=0; $i<$count;$i++) {
    ///some code

    }

    $s3 = microtime(true);

    print $s3-$s2.PHP_EOL;

    =========================

    0.13777184486389
    0.090176105499268

  6. Michael says:

    I’m surprised by some of the negative comments here. Even if it’s just a small optimization, it’s still better coding. And it all adds up. I like these PHP myths and hope you continue them.

Trackbacks/Pingbacks

  1. Tweets that mention PHP Mythbusters: Count inside for loop is slow | CodeForest -- Topsy.com

Leave a Reply