PHP optimization Tips

PHP Optimization Tips

There are many ways to improve the way you write your PHP code. And we can easily increase the efficiency of our code just by putting in some effort during development. However, there might be some unknown information that you might not aware in PHP that can help improve your code. In this article, i will try to provide you with some tips that can serve as micro optimization for your code and could also add on to the list of knowledge that you have in PHP. We will also look at many benchmarking of these tips where possible!

  • calling an object method is faster than trapping 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
  • 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 (“…”)
  • per 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.