Your reply piqued my curiosity so I whipped together a script that times the
execution of a foreach(), a while() and a for() loop executing the same
commands.  The results were rather surprising in some ways but not really
overall.

The while() loop is, as you stated, is quicker than a foreach() loop.
However, the for() loop is the fastest of all three.  Below are the results
of three tests:

Timed foreach() loop: 0.00766 sec.
Timed while() loop: 0.00689 sec.
Timed for() loop: 0.00676 sec.

Timed foreach() loop: 0.00768 sec.
Timed while() loop: 0.00688 sec.
Timed for() loop: 0.00677 sec.

Timed foreach() loop: 0.00770 sec.
Timed while() loop: 0.00689 sec.
Timed for() loop: 0.00674 sec.

The loops were parsing the text in a text file.

Again, we're talking about going down to 13/100,000th-second as an average
speed gain with a for() loop over a while() loop.  The average difference
between foreach() and while() is considerably larger, approximately
79/100,000th.  But again, you'd have to run through the complete execution
of the loop (53 lines of text in the file) 1,266 times to lose a single
second between foreach() and while().  A minimal gain in speed; I was just
mentioning it because it's easier to read a foreach() loop.  But in all
fairness, because the for() loop was quickest, here is the code converted to
for():

function check_file($filename) {
    if (!$lines = file($filename)) {
        return false;
    }
    for ($i = 0; $ < sizeof($lines); $i++) {
        $num_pipes = substr_count($lines[$i], '|');
        if ($num_pipes < 2 || $num_pipes > 4) {
            return false;
        }
    }
    return true;
}


I performed the test purely out of curiosity, not pride :)  Thanks for the
idea though, it was interesting to see the results.

Mike Frazer

PS - If you'd like the code for my Timer class, email me off-list and I'll
send it to you.



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to