PHP Optimization Tips: Get the Most Out of Your Applications

December 19th, 2011 Leave a comment 4 comments
Like the article?
PHP Optimization

Like any scripting language, PHP can be used in a variety of applications. The down-side for most programmers is that when they learn how to write PHP, they do not always learn how to write PHP with speed and optimization in mind. This article addresses five ways you can improve your code with minor changes that will yield large gains as well as teach you how to become a better PHP developer.

One of the most important things you can do when improving PHP application performance is begin measuring your application to find a baseline performance time for different parts of your application. If you do not know which parts of your application are slow or have bottlenecks, you will not know where to begin optimizing your code for better performance. There are many commercial and free applications that can be used to measure PHP performance. See the article PHP Profilers Compared for further information.

1. Use echo instead of print

Let’s begin with an easy one that requires a simple change but a big gain. The two main PHP functions for printing data to the client are echo and print. echo is a faster, more efficient call than print and will result in an 8 percent gain in performance per call. This is an excellent first step in optimization.

2. Use pre-increment instead of post-increment

Any PHP developer can tell you that PHP allows a pre-increment (++$foo) and a post-increment ($foo++), however most do not realize that pre-increment is much faster than post-increment by almost 10 percent! If you make the switch from post- to pre-incrementing you can make several mini-optimizations all over your site that will add up to big gains. This is especially important if you perform increments inside of loops as the gain will increase with each iteration.

3. Avoid error suppression operator

The PHP error suppression operator (@) is a nice way to avoid generating warnings or errors in your PHP scripts, usually because the error behavior is warranted but it is OK to ignore the warning. However, many developers use the suppression operator in a way that is inefficient, thus creating a slow-down in your script. Here are a few ways NOT to use the @:

As a replacement for isset: Often in PHP we have variables that we are not sure are set. An easy mistake for a new developer to make is to use the error suppression operator instead of using isset. For example:

$foobar = @$foo;

While the syntax seems nice and easy to read the performance of this kind of operation is abysmal when compared to isset which can perform this task at twice the efficiency.

if (isset($foo)) {
    $foobar = $foo;
} else {
    $foobar = NULL;
}

4. Use array_pad

With the list construct: A common case when assigning multiple variables from an array is to use the list construct with the explode function to split the string and set the parts of the list to each variable, like so:

list($foo1, $foo2, $foo3) = explode('/', 'var1/var2/var3');

However, the problem is then created where you may not be bringing in as many variables for each part of the list. If you are missing a variable or two when you explode you will get a nice notice from PHP. The usual response to this is to use the error suppression operator to dismiss the error.

@list($foo1, $foo2, $foo3) = explode('/', 'var1/var2');

In this case, $foo3 will be set to NULL and your script will suffer a speed penalty for use of the @ operator. To help with this problem it is better to use array_pad to only fill the array with the number of variables that you have instead of causing and suppressing an error at the cost of your performance. Here is a better way:

list($foo1, $foo2, $foo3) = array_pad(explode('/', 'var1/var2'), 4, NULL);

Maybe not the nicest looking code but definitely the fastest and most reliable way to perform this kind of operation.

5. Initialize local variables

Another small change you can make that is also good coding practice is to always initialize your local variables. Not only does it take longer to assign and use a local variable that has not been initialized but it is 9-10 times faster to increment an already initialized local variable. Once again, good coding style allows us to get larger gains in performance. This can go hand-in-hand with the idea that the use of local variables is faster than global variables performing the same operation.

6. Use single quotes in indexes

Finally, when specifying indexes, be sure to use single quotes around the name versus no quotes to improve script performance. Without the quotes the script interpreter must guess whether or not you want an index or a constant which will slow down the script down for each index. For example:

$row['foo'] versus $row[foo];

Ultimately you would get the same result but using the single quotes around the index name will perform seven times faster than if the script has to make the determination.

Conclusion

In the end, the best thing you can do to create better PHP code is to learn as much as possible of your chosen development environment, i.e. Apache, IIS, and Your Database. The deeper your knowledge of each piece the better you will become at using these different technologies together and finding the strengths and weaknesses. Practice is the key to better understanding and learning as well as working toward writing better, faster and more optimized code. We can help too. If you are looking to become a better PHP developer, consider enrolling in one of our hands-on PHP training courses!

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!

4 comments

  1. Mario says:

    Single quotes, echo, pre-increment. Doesn’t get more useless than those advises.

    If you don’t want to do pointless microoptimizations, then use the xdebug profiler. Look for *factual* speed drains, not fictional ones. Second-long database queries are the first thing to optimize, not the silly nanoseconds with minor syntax tweaks.

    • Michael Dorf says:

      Thanks Mario, but you missed the point. These are good all-around practices to follow as you build your app. I am not asking you to go through you entire existing app and replace all post-increments with pre-increments. Following these tips does not preclude using a profiler. On the contrary, the article asks you to do so.

  2. Yohan says:

    I second Mario on that one. These micro-optimization while good to know about, for best-practices, are really nothing compared to sluggish DB queries, or IO response times.

    Plus if you are really looking at microseconds optimization you wouldn’t be using PHP in the first place or at least do some kind of opcode caching like APC or Zend caching. I would say making sure that mastering caching techniques (opcode, queries results, entire pages or portions of pages) will get you much much further than this.

    But thanks Michael anyway for this article, for those starting with PHP (with no other language as prior experience) are better off keeping these in mind.

  3. Niks says:

    Thanks for sharing this. Tip regarding initializing local variable is great. Because of the flexibility most of the developers don’t initialize them.

    Though not related directly, you should also use smarty which helps to keep your business and coding logic separate and thus help you to focus on coding

Comment