12 PHP optimization tips

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. Avoid magic like __get, __set, __autoload
  3. require_once() is expensive
  4. Use full paths in includes and requires, less time spent on resolving the OS paths.
  5. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
  6. See if you can use strncasecmp, strpbrk and stripos instead of regex
  7. preg_replace is faster than str_replace, but strtr is faster than preg_replace by a factor of 4
  8. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  9. Error suppression with @ is very slow.
  10. $row[‘id’] is 7 times faster than $row[id]
  11. Error messages are expensive
  12. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.

As blogged by alexmoskalyuk

error_reporting(E_ALL); make code faster

The single most important thing I tell people who use PHP is to turn error reporting to its maximum level. Why would I want to do this? Generally the error reporting is set at a level that will hide many little things like:

  • declaring a variable ahead of time,
  • referencing a variable that is not available in that segment of code, or
  • using a define that is not set

These factors might not seem like that big a deal — until you develop structured or object oriented programs with functions and classes. Too often, writing code with the error reporting turned up high would cost you hours as you scoured long functions that didn’t work because a variable was misspelled or not accessible.

PHP won’t tell you anything in that case it’ll just create the new variable for you and initialize it to zero. The remedy is to put the following line at the top of every PHP document as you develop:

error_reporting(E_ALL);

It simply forces the error reporting to be at its highest level. Try putting this line in other PHP programs, and more often than not you’ll receive a barrage of warning messages that identify all the potentially wrong elements of the code.

Eventually this when enabled, will force you to write cleaner, structured and fast code.