Re: Performance: While or For loop
| From: | Travis Doherty | Date: | Fri, 23 Mar 2007 05:24:45 +0000 |
| Subject: | Re: Performance: While or For loop | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-251153@lists.php.net to get a copy of this message | ||
Tijnema ! wrote:
> On 3/22/07, Jon Anderson <janderson@gamingsolutions.ca> wrote:
>
>> Your test isn't exactly fair. The for loop has no statements in it, and
>> the while loop has one. Your tests show while as approx 7% faster, while
>> a modified test shows an approximate 30% speed improvement:
>>
>> Do this:
>>
>> for ($i=0;$i<10000000;$i++) {}
>>
>> v.s.:
>>
>> $i = 0;
>> while ($i++ < 10000000) {}
>
This has been asked many times, probably likewise for every language.
Search for the same question on the C programming language for a more in
depth discussion of this and to find out why one way is faster than the
other...
Major factor: Don't forget the difference between pre and post increment
operators. $i++ and ++$i.
For reference this is my PHP test script and results:
{{{
tdoherty@gamma tdoherty $ cat ./forwhile.php
<?
$i=0; $start = microtime(TRUE);
for ($i=0; $i<100000; ++$i) {}
echo sprintf("For pre-increment ($i): %0.3f\n",microtime(TRUE) - $start);
$i=0; $start = microtime(TRUE);
for ($i=0; $i<100000; $i++) {}
echo sprintf("For post-increment ($i): %0.3f\n",microtime(TRUE) - $start);
$i=0; $start = microtime(TRUE);
while (++$i < 100000) {}
echo sprintf("While pre-increment ($i): %0.3f\n",microtime(TRUE) - $start);
$i=0; $start = microtime(TRUE);
while ($i++ < 100000) {}
echo sprintf("While post-increment ($i): %0.3f\n",microtime(TRUE) - $start);
?>
tdoherty@gamma tdoherty $ php ./forwhile.php
For pre-increment (100000): 0.035
For post-increment (100000): 0.060
While pre-increment (100000): 0.029
While post-increment (100001): 0.056
}}}
After multiple runs I see that the for pre-increment loop is fastest.
Note that the while loop with a post-increment runs once more than with
a pre-increment.
Everytime I run, the results are *very* different, though still fall
within similar comparitive domains.
Travis Doherty