10 Performance Tips to Speed Up PHP

Even the most experienced programmer can be lazy. After all, what are a few milliseconds of extra load time here or there? Users won’t notice, right?

That sort of thinking is a slippery slope, though. A fraction of a second here or there, measured over thousand of visits, can add up to lost conversions. A little extra processing time per execution, over millions of executions, can add up to significant power consumption and wear and tear on the server. And since most good programming habits require no additional work on the part of the programmer, there’s a real business case to be made against lazy programming.

It’s time to break out of those lazy habits and start coding with performance in mind. Practice these ten PHP performance tips and watch your code go from sluggish to speedy in no time.

  1. Use echo instead of print(). As a language construct rather than a function, echo has a slight performance advantage over print().
  2. Echo with commas, not periods. I’m a repeat offender of this one. If you use periods, PHP has to concatenate the string before it outputs. If you use commas, it just outputs them in order with no extra processing.
  3. Avoid function tests in loop conditionals. If you’re looping through an array, for example, count() it beforehand, store the value in a variable, and use that for your test. This way, you avoid needlessly firing the test function with every loop iteration.
  4. Use include() and require() instead of include_once() and require_once(). There’s a lot of work involved in checking to see if a file has already been included. Sometimes it’s necessary, but you should default to include() and require() in most situations.
  5. Use full file paths on include/require statements. Normalizing a relative file path can be expensive; giving PHP the absolute path (or even “./file.inc”) avoids the extra step.
  6. Favor built-in functions over custom functions. Since PHP has to take the extra step of interpreting your custom functions, built-in functions have a performance advantage. More importantly, there are a lot of useful built-in functions that you may never learn about if you always default to writing your own.
  7. Avoid needlessly copying variables. If the variable is quite large, this could result in a lot of extra processing. Use the copy you already whenever possible, even if it doesn’t look pretty (e.g., $_POST['somevariable']).
  8. Pass unchanged variables to a function by reference rather than value. This goes hand-in-hand with the point about needlessly copying variables. Much of the time, your functions only need to use the values from their parameters without changing them. In such cases, you can safely pass those parameters by reference (e.g., function(&$parameter) rather than function($parameter)) and avoid having to make memory-intensive copies.
  9. Debug with error_reporting(E_ALL). Every warning is a performance improvement waiting to happen, but only if you can see it. Cleaning up warnings and errors beforehand can also keep you from using @ error suppression, which is expensive. Just don’t forget to turn off error reporting when you’re done; warnings and errors are expensive as well.
  10. Ditch double quotes for single quotes. There’s some disagreement, but the common wisdom is that PHP has to do extra processing on a string in double quotes to see if it contains any variables. Concatenation with single quotes is marginally faster.


Tips from this article were pulled from the following sources.



18 Responses to “10 Performance Tips to Speed Up PHP”

  1. mark on July 13th, 2009 5:33 am

    This tips really help me a lot and make me pursue to really write my code in a proper manner.

  2. Stephen Ward on July 13th, 2009 5:47 am

    Glad you liked them, Mark. :)

  3. PERECil on July 15th, 2009 9:33 am


    Just some notices after some tests:

    4. Didn’t see any difference when switching from (include|require)_once to (include|require). Tested on a test website with more than 20-30 requires.

    10. Tested in a for loop, i didn’t get any difference.

    My tests were done with php 5.2+

  4. Stephen Ward on July 15th, 2009 9:40 am

    Thanks for testing, PERECil. Some of these tips may very well be dated compared to the latest versions of PHP. I know there’s a lot of debate about single versus double quotes, which is why I included that tip at the end where other guides may have included it at the beginning. Out of curiosity, did you test the others, and, if so, how did they pan out?

  5. Phil on August 23rd, 2009 5:50 am

    Re point 7, needlessly copying variables. Using $_POST['somevariable'] over say $somevar = $_POST['somevariable'] and then accessing $somevar many times is much slower than just using $somevar. PHP has to lookup the name in the POST array each time.

  6. Weekly Link Roundup – 2009-11-29 | Unemployed Developer on November 30th, 2009 1:05 am

    [...] I like to read about these performance tips even though I know and do my best to practice them in my code. I think it’s important to always ensure your code not only works but works efficiently.. Read More [...]

  7. texxs on February 12th, 2010 2:52 pm

    Any tips for speeding up the initial load (caching won’t help here, I believe), that has a whole bunch of very tiny (like 8 characters long) includes?
    http://decksanfrancisco.com/prices/san-francisco-decking-prices.php is what I’m talking about. Each individual price (not the image, nor the description) is a php include.

  8. Stephen Ward on February 15th, 2010 12:47 pm

    Without knowing more about your setup, Texx, I can’t say for sure, but my gut tells me that moving your included information into a database and pulling it out with a query would vastly simplify things for you. For example, you might set up a MySQL database, propagate it with your pricing information, and pull the data into a $prices array with something simple like this:

    mysql_connect('hostname', 'username', 'password');
    $prices = mysql_query("SELECT product_id, price FROM decking_prices");
    $price = array();
    while ($price_data = mysql_fetch_object($prices)){
    $price[$price_data->product_id] = $price_data->price;

  9. Amy on June 4th, 2010 3:47 am

    Thanks for testing, PERECil. Some of these tips may very well be dated compared to the latest versions of PHP. I know there’s a lot of debate about single versus double quotes, which is why I included that tip at the end where other guides may have included it at the beginning. Out of curiosity, did you test the others, and, if so, how did they pan out?

  10. Speeding up your PHP code « KNDB Inc on October 20th, 2010 9:24 am

    [...] Stephen Ward shares how to write efficient code with PHP. He gives advice such as “Use echo instead of print().” and “Ditch double quotes for single quotes.”. But as pointed out by the commenters, some of these tips are probably outdated or by being taken care of by cache optimizers mentioned early in this article. Bookmark this on Delicious Tweet this | technical document | October 20, 2010 at 10:17 pm website renewal » Tagsphp Categories [...]

  11. PHPのスピードの向上 « Layer8 Tech on November 21st, 2010 12:35 am

    [...] Stephen Ward は 効率的なPHPの書き方を示してくれます。. “echoの代わりにprint()う” や “二重引用符の代わりに一重の引用符を使う” などのアドバイスです。 しかし 他の方がコメントで述べられているように、これらのアドバイスは古くて、おそらくキャシュのの最適化によって意味のないものになっているでしょう。 Tweet [...]

  12. Webapplications: scale or you get killed | CTO OPs on March 17th, 2012 9:51 am

    [...] pretty good Article on improving PHP [...]

  13. toraj on August 8th, 2012 5:25 am

    I tested comma vs periods with simple line :

    echo “hello ” , “hello ” , “helo ” , “hello ” , “hello ” , “helo ” , “hello ” , “hello ” , “helo “;

    and also

    echo “hello ” . “hello ” . “helo ” . “hello ” . “hello ” . “helo ” . “hello ” . “hello ” . “helo “;

    and running time with comma is greater than dot!!!

    with dot it is 0.00026893615722656 but with comma it is 0.0014798641204834, and as far as I know 0.0002 is smaller than 0.001.

    is there anything wrong with my test ?

  14. Werewolf on August 21st, 2012 3:07 pm

    Hi, nice post. But your tip

    Use include() and require() instead of include_once() and require_once().

    is not very useful because I run some tests and this is the output:


    Windows 7, Intel Core i3 2.30 GHz, 4 GB RAM DDR3 etc.

  15. spec on August 24th, 2012 8:43 am

    “8. Pass unchanged variables to a function by reference rather than value.”
    Actually it’s the other way round, passing values is faster in PHP, as it uses the ‘copy on write’ technique.

  16. Stephen Ward on September 8th, 2012 8:22 am

    Re:toraj, Werewolf, and spec, given that this post is more than three years old, I would expect some of the guidance to have changed by now. It only makes sense for PHP and server configurations to change over time to accommodate the way most people program.

    All the better for me, since I’m still a repeat offender of many of these tips. ;)

  17. Aaron Wright on July 23rd, 2013 6:55 pm

    Nice list of tips. But when it comes to copying $_GET or $_POST variables, I thought this was usually done for security reasons. I did more searching and found that there might be some truth to that (see http://phpsec.org/projects/guide/1.html). In short, the suggested method appears to be validating the data and if it is clean, then save the cleaned up version to it’s own variable and use that. Is this correct?

  18. Peter on December 4th, 2013 7:57 pm

    ad17 Aaron:copying variables means extra memory resources. Copying for security reasons is a bad habbit. No guarantee you made your variable safe! Best habbit: ALL USER INPUT (POST/GET/COOKIES/HEADER-INFO) ARE DANGEROUS VALUES!
    You just ALWAYS consider these values as extremely dangerous. Consequent escaping of all these values are critical for your sites safety. After made safe, there is absolutely no reason to copy them to other variabels. Concentrate on good escaping, renaming/copying values isn’t a safety procedure. It’s even worse: you dont recognize the variable was actually userinput. So copying is a real bad habbit too.

Share Your Thoughts