I did some small tests in PHP on loops. I do not know if my method is good.
I found that the reverse loop is faster than the regular loop.
I also found that the while loop is faster than the for loop.
Customization
<?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
Difference for cycle
normal for: 1.0908501148224
reverse for: 1.0212800502777
normal - reverse: 0.069570064544678
Cycle difference
normal so far: 1.0395669937134
vice versa: 0.99321985244751
normal - reverse: 0.046347141265869
Difference in for-loop and while-loop
inverse for - inverse while: 0.0280601978302
Questions
My question is: can someone explain these differences in the results? And is my benchmarking method correct?
source share