Tuesday, March 10, 2009

PHP micro-optimization tips

  • calling an object method is faster then traping it with with "__call"
  • calling a "static" method is faster then an object method
  • calling a function is faster then calling a static method
  • accessing a local variable is faster then then a global variable
  • accessing a global variable is faster then an object property
  • accessing an object property is faster then trapping it with "__get" and "__set"
  • accessing an initialized variable is faster then accessing an uninitialized variable
  • absolute paths in "include" and "require" are faster then relative
  • merging several scripts in one file and then including it is faster then several includes
  • "switch" is faster then "if ... else if ..." in some cases
  • do not use regexs for simple string processing tasks
  • avoid @ (error control operator)
  • avoid notices and warnings in your scripts
  • avoid unused variables and unused method parameters
  • adding method parameter increases calling time
  • adding method parameter type hint increases calling time
  • unset variables that contain large amount of data or circular references
  • $_SERVER['REQUEST_TIME'] contains script startup time
  • cache page output or result of resource-consuming functions
  • "echo" is faster than "print"
  • "echo" accepts several arguments, you can use it instead of string concatenation
  • "ob_start()" and "ob_end_clean()" is may be better then several string concatenations
  • strings in single quotes ('...') are processed faster then strings in double quotes ("...")
  • pre-increment (++$i) is faster then post-increment ($i++)
  • "isset" is a faster alternative to "array_key_exists"
  • an array is a faster alternative to a class with several fields
  • "foreach" is better then "for" in many cases
  • open resources (files, database connections, sockets) right before using them, free resources as soon as you do not need them
  • do not fetch database fields which you do not use in your script
  • use prepared database statements
  • combine several queries in one when database supports it

No comments: