Why a reverse loop is faster than a regular loop (including a test)

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?

+4
source share
1 answer

With the loopback loop, you only perform one search for variables per iteration:

 $w > 0 // <-- one lookup to the $w variable $w < $counter // <-- two lookups, one for $w, one for $counter 

This is why the converse is somewhat faster. In addition, the while loop has only one operation for each iteration:

 $w < $counter // <-- one operation while loop $w < $counter ; $w++ // <-- two operation for loop 

Of course, you have this extra operation inside the loop code block, but I'm not sure exactly why it is faster (maybe someone can fill the gap there). You will notice that the time difference is minimal, as these operations are still very fast. Such microoptimizations are most effective on very large cycles.

+4
source

Source: https://habr.com/ru/post/1306529/


All Articles