PHP tips and tricks to improve website speed

PHP tips and tricks to improve website speed

  • Echo is faster than print
  • 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
  • Use sprintf instead of variables contained in double quotes, it’s about 10x faster
  • Unset or null your variables to free memory, especially large arrays
  • Avoid magic like __get, __set, __autoload
  • Use require() instead of require_once() where possible
  • Use full paths in includes and requires, less time spent on resolving the OS paths
  • 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
  • “else if” statements are faster than select statements aka case/switch
  • Error suppression with @ is very slow
  • To reduce bandwidth usage turn on mod_deflate in Apache v2 or for Apache v1 try mod_gzip
  • Close your database connections when you’re done with them
  • $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
  • Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags
  • ++$i is faster than $ i++, so use pre-increment where possible
  • In OOP, Methods in derived classes run faster than ones defined in the base class
  • 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
  • Avoid the PHP mail() function header injection issue

2 thoughts on “PHP tips and tricks to improve website speed

  1. Hi. A good article but I could not get the reason of “In OOP, Methods in derived classes run faster than ones defined in the base class”. Can you please explain?

Leave a Reply

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