on Mythbusters

PHP Mythbusters: Count inside for loop is slow

11 comments
code
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

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.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



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

  • SF

    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.

  • Zvonko

    Thanks for the comment. Typo is corrected now.

  • mario

    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

      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.

    • http://andreasnurbo.com Andreas Nurbo

      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.

  • http://www.electrictoolbox.com/ Chris

    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/

  • http://www.zhaokunyao.com huarong

    <?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

  • Michael

    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.

  • http://karl.hiramoto.org/ Karl Hiramoto

    Yes, It’s bad style and inefficient, more so the larger your array is.

    <?php

    $a = array_fill(5, 10000000, 'test');
    $calc = 0;

    $s1 = microtime(true);
    for($i=0; $i<count($a);$i++) {
    $calc = $i + $calc + count($a); // do some work
    }
    $s2 = microtime(true);
    printf("count in loop = %.6f \n", $s2-$s1);

    $calc = 0;
    $s1 = microtime(true);
    $length = count($a);
    for($i=0; $i

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

    count in loop = 4.451260
    count outside loop = 1.180692

  • http://karl.hiramoto.org/ Karl Hiramoto

    Yes, It’s bad style and inefficient, more so the larger your array is. Modified test not measuring the time it takes to print.


    <?php
    $a = array_fill(5, 10000000, 'test');
    $calc = 0;
    $s1 = microtime(true);
    for($i=0; $i<count($a);$i++) {
    $calc = $i + $calc + count($a); // do some work
    }
    $s2 = microtime(true);
    printf("count in loop = %.6f \n", $s2-$s1);
    $calc = 0;
    $s1 = microtime(true);
    $length = count($a);
    $length = count($a);
    for($i=0; $i
    =====================
    count in loop = 4.451260
    count outside loop = 1.180692