PHP micro-optimization tips

Why “micro-”? Because changing logic of your application may give you much better performance boost than all these tips. But they still can make your code better. You always need to output something, why do not use echo instead of print?

  • calling an object method is faster than catching it with with __call
  • calling a static method is faster than an object method
  • calling a function is faster than calling a static method
  • accessing a local variable is faster than a global variable
  • accessing a global variable is faster than an object property
  • accessing an object property is faster than trapping it with __get and __set
  • accessing an initialized variable is faster than accessing an uninitialized variable
  • absolute paths in include and require are faster than relative
  • merging several scripts in one file and than including it is faster than several includes
  • switch is faster than if ... else if ... in some cases
  • if ... elseif ... may be faster then switch when variables are checked with strict equality comparison (===)
  • 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
  • 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 than several string concatenations
  • strings in single quotes ('...') are processed faster than strings in double quotes ("...")
  • pre-increment (++$i) is faster than 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 than for in many cases

This micro-optimisations was tested with PHP5 when it was a mainstream.