50+ PHP optimisation tips revisited

After reading an article some time ago entitled “40 Tips for optimizing your php Code” (and some others that are suspiciously similar), I decided to redo it, but properly this time with more accurate tips, providing references and citations for each and every one.

The result is this list of over 50 PHP optimisation tips…

Update: The list is more like 50+ PHP tips and tricks these days.

Enjoy!

  1. echo is faster than print. [Citation]
  2. Wrap your string in single quotes (‘) instead of double quotes (“) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string. [Citation]
  3. Use sprintf instead of variables contained in double quotes, it’s about 10x faster. [Citation]
  4. Use echo‘s multiple parameters (or stacked) instead of string concatenation. [Citation]
  5. Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts. [Citation]
  6. Unset or null your variables to free memory, especially large arrays. [Citation]
  7. Avoid magic like __get, __set, __autoload. [Citation]
  8. Use require() instead of require_once() where possible. [Citation]
  9. Use full paths in includes and requires, less time spent on resolving the OS paths. [Citation]
  10. require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference. [Citation]
  11. Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime(). [Citation]
  12. PCRE regex is quicker than EREG, but always see if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead. [Citation]
  13. When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4. [Citation]
  14. str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace. [Citation]
  15. “else if” statements are faster than select statements aka case/switch. [Citation]
  16. Error suppression with @ is very slow. [Citation]
  17. To reduce bandwidth usage turn on mod_deflate in Apache v2 [Citation] or for Apache v1 try mod_gzip. [Citation]
  18. Close your database connections when you’re done with them. [Citation]
  19. $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant. [Citation]
  20. Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags. [Citation]
  21. Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on. [Citation]
  22. PHP scripts are be served at 2-10 times slower by Apache httpd than a static page. Try to use static pages instead of server side scripts. [Citation]
  23. PHP scripts (unless cached) are compiled on the fly every time you call them. Install a PHP caching product (such as memcached or eAccelerator or Turck MMCache) to typically increase performance by 25-100% by removing compile times. You can even setup eAccelerator on cPanel using EasyApache3. [Citation]
  24. An alternative caching technique when you have pages that don’t change too frequently is to cache the HTML output of your PHP pages. Try Smarty or Cache Lite. [Citation]
  25. Use isset where possible in replace of strlen. (ie: if (strlen($foo) < 5) { echo “Foo is too short”; } vs. if (!isset($foo{5})) { echo “Foo is too short”; } ). [Citation]
  26. ++$i is faster than $ i++, so use pre-increment where possible. [Citation]
  27. Make use of the countless predefined functions of PHP, don’t attempt to build your own as the native ones will be far quicker; if you have very time and resource consuming functions, consider writing them as C extensions or modules. [Citation]
  28. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview. [Citation]
  29. Document your code. [Citation]
  30. Learn the difference between good and bad code. [Citation]
  31. Stick to coding standards, it will make it easier for you to understand other people’s code and other people will be able to understand yours. [Citation]
  32. Separate code, content and presentation: keep your PHP code separate from your HTML. [Citation]
  33. Don’t bother using complex template systems such as Smarty, use the one that’s included in PHP already, see ob_get_contents and extract, and simply pull the data from your database. [Citation]
  34. Never trust variables coming from user land (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML. [Citation]
  35. For security reasons never have anything that could expose information about paths, extensions and configuration, such as display_errors or phpinfo() in your webroot. [Citation]
  36. Turn off register_globals (it’s disabled by default for a reason!). No script at production level should need this enabled as it is a security risk. Fix any scripts that require it on, and fix any scripts that require it off using unregister_globals(). Do this now, as it’s set to be removed in PHP6. [Citation]
  37. Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5 hash. [Citation]
  38. Use ip2long() and long2ip() to store IP addresses as integers instead of strings. [Citation]
  39. You can avoid reinventing the wheel by using the PEAR project, giving you existing code of a high standard. [Citation]
  40. When using header(‘Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible. [Citation]
  41. In OOP, if a method can be a static method, declare it static. Speed improvement is by a factor of 4. [Citation].
  42. Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable. [Citation]
  43. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. [Citation]
  44. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. [Citation]
  45. Just declaring a global variable without using it in a function slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists. [Citation]
  46. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance. [Citation]
  47. Methods in derived classes run faster than ones defined in the base class. [Citation]
  48. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations. [Citation]
  49. Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory. [Citation]
  50. Never trust user data, escape your strings that you use in SQL queries using mysql_real_escape_string, instead of mysql_escape_string or addslashes. Also note that if magic_quotes_gpc is enabled you should use stripslashes first. [Citation]
  51. Avoid the PHP mail() function header injection issue. [Citation]
  52. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
  53. RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English. Please USE IT! [Citation]

If you still need help, try #PHP on the EFnet IRC Network. (Read the !rules first).

Also see:

Think you’re a PHP guru now? See if you can answer these questions.

About admin

Website Administrator
This entry was posted in Development and tagged , . Bookmark the permalink.

38 Responses to 50+ PHP optimisation tips revisited

  1. Imran Nazar says:

    All good points, but most of these are low-level optimisations. In the words of the indomitable Knuth, “premature optimization is the root of all evil”.

    Before looking into whether to use echo or print, it may be more advisable to check the algorithm being used by the code, and seeing whether it can be improved. The small tweaks discussed above may produce a few percentage points of speed increase, but an improved algorithm can yield speedups in the orders of magnitude.

    This article will prove useful in dissuading the endless flamewars over whether to use require_once, mind you.

  2. Pingback: 50+ PHP Optimisation Tips | Gilbert "Gilbitron" Pellegrom

  3. Chang Yeng says:

    Hi,
    thank you very much. I learned so many thing from this article. good luck change yeng

  4. Pingback: PHP Optimization Tips | ProgTuts

  5. Pingback: Dicas para otimizar códigos PHP | desenvolvimento para web

  6. Pingback: HM2K.com » For VS While in PHP

  7. Pingback: Optimize your PHP Code (Tips) « PLAY with PROBLEMS

  8. Pingback: Code My Media » 50+ PHP optimization tips

  9. Pingback: CHECKMATE » Optimize your PHP Code - Tips, Tricks and Techniques

  10. Peter says:

    Please update the Smarty link !

  11. This is regarding the 3rd point: ‘Use sprintf instead of variables contained in double quotes, it’s about 10x faster.’

    The citation which you are providing is linking to another page ‘http://fi.php.net/manual/en/function.print.php#66392′ which is providing the results of the test. What he is saying is that DONT use sprintf.
    In his words:
    “Third, stay away from heredoc, and absolutely stay away from [s]printf. They’re slow, and the alternatives are there.”

    Could you tell me what is right? or whether I interpreted it wrongly? In that case, I am sorry. :)

  12. Phil says:

    Micro-optimization almost never makes sense.

    Have a look at Stas’s superb list instead: http://php100.wordpress.com/2009/07/13/php-performance/

  13. Max says:

    Great article, thank you so much!

  14. K says:

    Great list. Good work. Some of your suggestions, such as $i++ vs ++$i are probably not relevant for most web sites, but it’s nice to know.

    I hate nitpickers, too bad that I am one of them today.

    Source:

    http://groups.google.com/group/make-the-web-faster/browse_thread/thread/ddfbe82dd80408cc

    I’m reposting the relevant points here.

    2: They have apparently improved string handling in the newer versions. “Benchmarks run against PHP 5.2 and 5.3 show that parsing double-quoted strings with interpolation is no slower (and often faster) than single-quoted strings using concatenation. When simple strings with no variables in them are used, the performance is clearly better with double-quoted strings due to implementation details in the engine. See the benchmark posted at .”

    4: This is exactly the opposite of correct advice. The engine handles multiple arguments to echo() in such a way that concatenation (or double-quoted string interpolation) is actually much faster. See the benchmark posted at .

  15. Someone says:

    I disagree with all of the MySQL escape stuff. Use prepared statements and your data will be sanitised for you. http://au.php.net/manual/en/mysqli.prepare.php

  16. D Mali says:

    I liked the list, but many of the citations are worthless: off-topic, unfounded or untested, etc. I was surprised at how much conjecture was used to ‘support’ conjecture.

    Perhaps the sources have changed their content(?). If not, please don’t pretend to be documenting something when all that is happening is circular intuition.

  17. Another someone says:

    @someone: Well it is in fact true that prepared statements sanitize user input automatically but that’s not the actual usage intention behind prepared statements. They exist for repeating an SQL query template multiple times with different parameters (e.g. inserting huge amounts of data). If you’re making use of a database query just once (which is the usual case in most PHP scripts) using the prepared statement mechanism, you have in reality two accesses to your database (1st preparing the statement, 2nd sending the data). If you make use of a plain SQL query it is just a single database access. So just go for the string escape function where applicable.

  18. Dzinepress says:

    really nice work you sharing here.

  19. Great tips thanks.
    As a beginner in php it will help me.

  20. Pingback: 45 Must Read PHP Articles and Resources

  21. Genta says:

    You are great

  22. Pingback: 50+ PHP optimisation tips revisited « HudchewMan's Diary

  23. Pingback: Must Read PHP Articles and Resources « UR-Technology

  24. Faruq Shaik says:

    Good article for php beginners . Thanks .

  25. I am a PHP programmer. I used to do lots of programming. But i didn’t think about is performance. I dont even thought about to keep a standard. I think here after i can follow some strict rules in php programming. Anyway thank you for sharing the list of optimization rules with us.

  26. Pingback: Heartdisc » Blog Archive » 50+ PHP optimisation tips

  27. Pingback: PHP Optimizasyon İpuçları | Aykut FARSAK

  28. Pingback: TutsBox 50+ PHP optimisation tips revisited

  29. Pingback: Les 52 commandements du développeur PHP… « L'antre du bricolo…

  30. Pingback: HM2K.com » Premature optimization is the root of all evil

  31. Hosting Best says:

    Have bookmarked this page for use while PHP’ing, thanks for putting these tips on one page

  32. DaiLaughing says:

    Point 2 is directly contradicted by the author’s citation for point 3 and that source doesn’t even mention sprintf. Badly investigated and misleading – keep clear.

  33. Sadek says:

    Great list. Good work. Some of your suggestions, such as $i++ vs ++$i are probably not relevant for most web sites, but it’s nice to know.

    I hate nitpickers, too bad that I am one of them today.
    Source: http://www.btips.net/2011/09/how-to-show-post-excerpt-in-wordpress-blog/

  34. djtechwork says:

    A very complete tips. The citation makes it greater..
    Thanks. It’s very useful for beginner like me

  35. deepak says:

    gr8 one :)

  36. Dre says:

    great list … thanks a bunch for taking the time to write it down.. saves months.. years of bumping into issues for a programmer..

    keep it up!

  37. Peter Smith says:

    A lot of these tips result in an insignificant increase in performance: 1, 2, and 4 are prime examples (not sure about 3; 5 is actually a good tip). In fact, tip 1 isn’t even always true – sometimes the opposite holds.

    You might say that any increase is better than nothing, but I’d say it’s just distracting away from more important performance aspects.

    Trim this list down to 10, and you’ve got a good list.

  38. Juan Mendes says:

    You should change the title of the post to “50 premature optimization techniques”. Joking aside, It’s fine to mention these, but you should make it clear that most of these techniques don’t yield real measurable improvements in code (unless the code is crafted for one of these rules).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>