Friday, September 10, 2004

Performance & tweaking : FOR vs. WHILE vs. DO-WHILE

just out of curiosity I wanted to see which one of these structures are faster. I believed that "for" will be the fastest but the tests proved I was wrong.
Anyway here is my code so you could try it yourselvs:


<?php
function getmicrotime()
{
   list(
$usec, $sec) = explode(" ", microtime());
   return ((float)
$usec + (float)$sec);
}

$count = 2000000;
$startFor = getmicrotime();
for (
$i=0; $i<$count; $i++)
{
    
//do nothing
}
$stopFor = getmicrotime();
echo
"\n<br> Time for for:",$stopFor-$startFor;

$startWhile = getmicrotime();
$i=0;
while (
$i<$count)
{
    
$i++;
}
$stopWhile = getmicrotime();
echo
"\n<br> Time for while:",$stopWhile-$startWhile;

$startDo = getmicrotime();
$i=0;
do
{
    
$i++;
}
while (
$i < $count);
$stopDo = getmicrotime();
echo
"\n<br> Time for do:",$stopDo-$startDo;
?>



And here are the times:
for: 2.078712940216064
while: 1.981828927993774
do: 1.936743974685669

As you can see for 2,000,000 iterations the do-while structure is almost 0.15 seconds faster than the for structure. This won't mean very much for small sites but in complex aplication where you'll have to handle many hits it will make a difference

2 Comments:

At 12:36 AM, Anonymous Anonymous said...

a variant on the first posting made... this performs slightly better:

while (--$i) {
//do nothing
}

as opposed to

do {
//do nothing
} while (--$i);

 
At 8:15 PM, Anonymous Anonymous said...

try this also:

for ($i=0; $i++<$count; )
...
it's the fastest one of those three in the article

-- spaze

 

Post a Comment

<< Home