If you need a fast loop, you have to deploy it or use a duff device.
You can also shorten the for-loop ( ) loop :
for ($var = 0; ++$var < 10; ) { // do nothing }
You can also shorten the do-while ( demo ) loop:
$var=0; do { echo "Hello"; } while (++$var < 10);
But the operation codes are the same.
And here is the modified version of the duff device from php.net:
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n log n)), and you're still worried about loop speed, unroll your loops using eg, Duff Device: <?php $n = $ITERATIONS % 8; while ($n--) $val++; $n = (int)($ITERATIONS / 8); while ($n--) { $val++; $val++; $val++; $val++; $val++; $val++; $val++; $val++; } ?>
(This is a modified form of the original Duff device because PHP does not understand how the original egregious syntax is.)
This is algorithmically equivalent to the general form:
<?php for ($i = 0; $i < $ITERATIONS; $i++) { $val++; } ?> $val++ can be whatever operation you need to perform ITERATIONS number of times. On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10 million) is: Duff version: 7.9857 s Obvious version: 27.608 s
source share