Website Speed Part 4 : PHP Programming for Speed

Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to reduce the amount of code, but again this is usually only for those that suffer with the luxury of having too much money and time.

I wish I had that luxury, to be able to spend twice as long on a problem to make a perfect solution. In truth I don’t most of the time, as I am out there getting new clients, making other products or not in the fortunate position to have a client with very deep pockets.

To counteract these things I have a bunch of methods stored in my head that allow me to choose the best path first time (I hope!). I am going to share these best practices with you so you can maybe do the same, maybe even better. If you have any great speed suggestions for coding, please comment and I will append it to this post.

Also, please note that this is not an exhaustive list. This is more of a pointer to things you should consider in your favorite coding language. Although this is for PHP specifically, I’ve tried to keep it as generic as possible to make it possible for all coders, no matter the language, to benefit.

Making IF ELSE smaller

IF is possibly the most used statement from all the programming languages, and I think the most used by a noob programmer (hey I was one once, I remember my code).

Common IF ELSE usage

          if ( $something == true ){
              $value = 'yes';
          }else{
              $value = 'no';
          }

Now using only IF

          $value = 'no';
          if ( $something == true ){
              $value = 'yes';
          }

As you can see all that has been done is that value is pre-set to ‘no’ and only gets changed to ‘yes’ if something is true. Both bits of code have the same outcome, one has less code.

If you only have 1 command inside the if statement then you can take things a little further. PHP does not require that you have the curly brackets when there is just one line.

          $value = 'no';
          if ( $something == true )
              $value = 'yes';

Ternary operators

We can go a stage further and have Ternary Operators. These are mathematical instructions that allow for a yes/no answer, just like IF.

IF presented as ternary operation

          $value = ( $something == true ) ? "yes" : "no" ;

Again the same IF ELSE statement, made much smaller. What it does is check the if the statement inside the brackets is either true or false, if it is true it will set value to be “yes”, if it is false it will set value to be “no”

syntax of ternary operators

          output = ( true/false condition ) ? true-value : false-value ;

It is not essential to have an output, as the true or false value could call a function and not return a value.

Using Range to create an array of numbers

Often people will code an array with just a bunch of numbers in it so that they can loop through it.

PHP code to create a select drop down list

          // selected item value
          $item = 12;
          // create array of numbers
          $array_of_numbers = array( 2,4,6,8,10,12,14,16 );
          // start the select 
          echo "<select name='myselect' >";
          foreach ($array_of_numbers as $number){
          // use terany operator to compare $number and $item, if the same make $selected = "selected"
          $selected = ( $number == $item ) ? "selected" : "" ;
          // echo option, with details filled in
          echo "<option value='" . $number . "' " . $selected . " >" . $number . "</option>";
          }
          echo "</select>";

Now the same thing shorter with range

          // selected item value
          $item = 12;
          // start the select
          echo "<select name='myselect' >";
          foreach ( range(2,16,2) as $number){
          // use ternary operator to compare $number and $item, if the same make $selected = "selected"
          $selected = ( $number == $item ) ? "selected" : "" ;
          // echo option, with details filled in
          echo "<option value='" . $number . "' " . $selected . " >" . $number . "</option>";
          }
          echo "</select>";

Range is a really handy thing, as what it does is created an array of numbers (integers). It has the following syntax in php:

          range($start_number, $end_number, $increment);

The only needed compulsory items are the start and end number, the increment defaults to 1, but can be any number you like.

A range function is available in most languages but is unfortunately not available in Javascript out of the box, so to make this same saving in code you would be best to use a FOR loop

FOR loop version

          // selected item value
          $item = 12;
          // start the select
          echo "<select name='myselect' >";
          for($number = 2; $number <= 16; $number = $number + 2){
          // use ternary operator to compare $number and $item, if the same make $selected = "selected"
          $selected = ( $number == $item ) ? "selected" : "" ;
          // echo option, with
          echo "<option value='" . $number . "' " . $selected . " >" . $number . "</option>";
          }
          echo "</select>";

Turbo charging the FOR loop

Many people like to use a for loop as they believe that it is faster than a foreach. While this is often true, it does not offer the flexibility of foreach and with the wrong programming techniques can be slower

The slower FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // loop through all the characters
            for($i=0; $i < strlen($text); $i++){
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
            }

The faster FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // get the length of the string
            $length = strlen($text);
            // loop through all the characters
            for($i=0; $i < $length ; $i++){
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
            }

The 2nd for loop is faster as it does not need to re-check the string length each time the loop runs. The first loop will check the string length 17 times with the text used

Making your code easier to maintain, and faster

I often see the same problem with my noob code when I re-visit it. The code is all written on 1 line and very long. Check this bit of code as an example:

          $html = "<input name='" . $name . "' id='" . $id . "' value='" . $value . "' class='" . $theclass . "' type='checkbox' " . $checked . " />";
          echo $html;

It works just fine, and will be ok for any implementation, but there are some problems with it. For example if the class is empty, it is wasteful to code the empty class setting. While this may not make so much difference to a Javascript implementation, as this is being generated on the server with PHP, you’d be sending extra bytes to the clients browser which are not required. This of course will make the most difference when making AJAX calls and waiting for the reply, where extra bytes can make much more of an impact.

An easier way to maintain

          $attributes = " name='" . $name  . "' ";
          $attributes .= " id='" . $id  . "' ";
          $attributes .= " value='" . $value  . "' ";
          $attributes .= ($theclass != '' )?  " class='" . $theclass  . "' " : "" ;
          $attributes .= ($selected == $value )?  " checked " : "" ;
          $html = "<input type='checkbox' " . $attributes  . " />";
          echo $html;

As you can see, much easier to read, much easier to maintain, and used on the server side will produce less HTML code.

Don’t echo every line only the final output

It’s much easier to echo every line, or pass control back to HTML, than it is to write every line to a variable, yet writing the output to a variable first and only echoing at the end is the faster way to process

The easy way to do things, with a few variations

    echo "<h2>" . $title . "</h2>"; ?>
    <small><?php echo date(); ?><small>

The more server friendly way to do things

    $output = "<h2>" . $title . "</h2>";
    $output .= "<small>" . date() . "<small>";
    echo $output;

OK, this is a very simplistic example of what you should do as it is only 2 lines and then output.

Rounding up

This is a very short list of things to help make your PHP coding faster and easier to maintain. There is of course many more things that you can do to reduce the amount of code that you do use, or the speed that it runs at.

Most of these techniques can be taken across to other programming languages, so when your coding in Javascript or .NET give it some thought and you will be making things much faster.

More from the Website Speed series…

Website Speed Part 1: Write More Efficient CSS →
Website Speed Part 2: Working With and Optimizing Images for the Web →
Website Speed Part 3 – Caching WordPress →

Author: (13 Posts)

Andy Killen has been working exclusively with the web since 1994 when he was Intel's internet engineer for Europe. Today he runs his own company phat-reaction.com as well as is the CTO of Speckyboy and was also part of the Adobe Fireworks CS6 beta test team. When Andy is not busy making websites, themes and plugins or giving training on website performance, wordpress or node.js, he can be found enjoying life in Amsterdam.

Comments