We're able to look at the big picture, yet still pay
attention to the details.

PHP Optimization Techniques

Unlike languages such as C++ or Java, PHP is a parsed language and does not have a complier that can inform the programmer about potential code tweaks, that's why when writing your PHP code remember about following tips that can improve PHP's performance:
 

  • Do not use functions within conditional statement of for loop.

    If you are looping through large arrays, make sure you avoid functions such as count() or sizeof() inside the for loop's conditional part. Consider following example:

    for ($i=0 ; $i<sizeof($array) ; $i++)
    {
         //process array elements
    }

    Function sizeof() is called during every iteration, that means if the length of $array is 1000, function sizeof() will be called 1000 times. Instead, define the size of an array outside the loop:

    $size = sizeof($array);

    for($i=0 ; $i<$size ; $i++)
    {
         //process array elements
    }

    Or write your loop as follows:

    for($i=sizeof($array) ; ($i--)>=0 ; )
    {
         //process array elements
    }
     
  • When passing objects and arrays to functions, make sure to use references.
     
  • Use include() rather than require_once(). The second function is more expensive since it keeps track of include files in your main script.
     
  • Avoid using multiple if, else if statements, use switch instead.
     
  • When dealing with regular expressions, consider using str_* functions for simple string operations. Using str_replace() works four times faster than preg_replace().
     
  • Reuse variables as much as you can, initiating new variables for accessing data that already has a reference in your code creates overhead.
     
  • For small applications, limit the use of OOP (object oriented programming). Each object and method consumes a lot of memory.
     
  • Make sure to close database connection after finishing working with it.
     
  • Avoid creating functions that are already predefined in PHP.
     
  • Cache as much as possible using modules such as memcache. Static HTML page generates up to 10 times faster than a PHP page which is re-parsed every time upon request unless cached.


PHP has greatly evolved since its first releases. Some optimization techniques are already implemented in the most recent version 5 such as automatic pass-by-reference when using objects as arguments. PHP is simply a great solution for the modern world wide web development.