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?
With the inverse for loop, you’re only doing one variable lookup per iteration:
This is why the inverse is slightly faster. Also, a while loop has only one operation per iteration:
Of course, you have that extra operation inside the loop’s code block, but I’m not sure exactly why that’s faster (maybe someone can fill in the blank there). You’ll notice the time difference is minimal, because these operations are still very fast. Such micro-optimisations are most effective on very large loops.