Why is an inverse loop faster than a normal loop (test included)
Posted
by Saif Bechan
on Stack Overflow
See other posts from Stack Overflow
or by Saif Bechan
Published on 2010-04-09T23:31:26Z
Indexed on
2010/04/09
23:33 UTC
Read the original article
Hit count: 323
I have been running some small tests in PHP on loops. I do not know if my method is good.
I have found that a inverse loop is faster than a normal loop.
I have also found that a while-loop is faster than a for-loop.
Setup
<?php
$counter = 10000000;
$w=0;$x=0;$y=0;$z=0;
$wstart=0;$xstart=0;$ystart=0;$zstart=0;
$wend=0;$xend=0;$yend=0;$zend=0;
$wstart = microtime(true);
for($w=0; $w<$counter; $w++){
echo '';
}
$wend = microtime(true);
echo "normal for: " . ($wend - $wstart) . "<br />";
$xstart = microtime(true);
for($x=$counter; $x>0; $x--){
echo '';
}
$xend = microtime(true);
echo "inverse for: " . ($xend - $xstart) . "<br />";
echo "<hr> normal - inverse: "
. (($wend - $wstart) - ($xend - $xstart))
. "<hr>";
$ystart = microtime(true);
$y=0;
while($y<$counter){
echo '';
$y++;
}
$yend = microtime(true);
echo "normal while: " . ($yend - $ystart) . "<br />";
$zstart = microtime(true);
$z=$counter;
while($z>0){
echo '';
$z--;
}
$zend = microtime(true);
echo "inverse while: " . ($zend - $zstart) . "<br />";
echo "<hr> normal - inverse: "
. (($yend - $ystart) - ($zend - $zstart))
. "<hr>";
echo "<hr> inverse for - inverse while: "
. (($xend - $xstart) - ($zend - $zstart))
. "<hr>";
?>
Average Results
The difference in for-loop
normal for: 1.0908501148224
inverse for: 1.0212800502777
normal - inverse: 0.069570064544678
The difference in while-loop
normal while: 1.0395669937134
inverse while: 0.99321985244751
normal - inverse: 0.046347141265869
The difference in for-loop and while-loop
inverse for - inverse while: 0.0280601978302
Questions
My question is can someone explain these differences in results? And is my method of benchmarking been correct?
© Stack Overflow or respective owner