A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

40 ways to optimize your PHP Code

A must read for PHP Programmers. Here is the first half:

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. echo is faster than print.
  3. Set the maxvalue for your for-loops before and not in the loop.
  4. Unset your variables to free memory, especially large arrays.
  5. Avoid magic like __get, __set, __autoload
  6. require_once() is expensive
  7. Use full paths in includes and requires, less time spent on resolving the OS paths.
  8. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
  9. See if you can use strncasecmp, strpbrk and stripos instead of regex
  10. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  11. 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.
  12. Error suppression with @ is very slow.
  13. $row[’id’] is 7 times faster than $row[id]
  14. Error messages are expensive
  15. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
  16. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  17. Incrementing a global variable is 2 times slow than a local var.
  18. Incrementing a object property (eg. $this->prop++) is 3 times slower than a local variable.
  19. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  20. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.

For the other half, go here.

This entry was posted in General and tagged , . Bookmark the permalink.

3 Responses to 40 ways to optimize your PHP Code

  1. Vijay says:

    Where is other 20 tips ?

  2. Headspin says:

    Ha, looks like you should add one for how to optimize pagination ;)

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>