Home » PHP developer » Optimisation by unrolling a PHP loop

Optimisation by unrolling a PHP loop

A good PHP programmer or developer will use a number of techniques to ensure the code produced is efficient.

This optimisation technique is a space-time tradeoff.  The technique is used to  optimise  PHP program’s run-time speed, but at the expense of the size of the code or code length.

Instructions that control loops (branching penalties) can be time consuming so the idea is to excute as much as you can in each PHP programs interation cycle. Loops are re-written, by a PHP programmer to repeated similar statements.

The techniques advantages for a PHP program are:

  • Significant gains PHP execution speed that will surpass any loss in speed due to the  progam  or  performance reduction due to program’s size.
  • Branching penalties are kept to a minimum.
  • The technique allows for pseudo parallel PHP statements execution

The techniques disadvantages for a PHP program are:

 

  • Increased is size of the PHP program with an attendant performance loss
  • The code may become less readable adding to maintenance issues
  • Use of functions may be compromised
  • Applying if statements  in the unrolled PHP code may also lead to loss in performance.

Example PHP 5 Code

Original PHP code

<?php 
for ($x = 0; $x <= 1000; $x++) {
     echo "Sales figures: $x, $sales[$x} <br>";
} 
?>

Unrolled version

<?php 
for ($x = 0; $x <= 1000; $x+5) {
    echo "Sales figures: $x, $sales[$x} <br>";
    echo "Sales figures: $x, $sales[$x+1} <br>";
    echo "Sales figures: $x, $sales[$x+2} <br>";
    echo "Sales figures: $x, $sales[$x+3} <br>";
    echo "Sales figures: $x, $sales[$x+4} <br>";
} 
?>

 

 

 

 

Support