The Premature Optimization Trap

Print

Recently I came across a blog post that promised to teach developers how to optimize PHP code in 15 steps. Right from the onset I was skeptical of such a post that consists of a cheat-sheet to follow akin to the 10 commandments in the name of optimization. I decided to read it anyway and sure enough it was riddled with shady advice.

The author opens with the following statement:

If you are a developer, it is essential for you to optimize your script early in the development process itself. Following the best practices while coding your PHP script is a good starting point to write a well optimized PHP code.

The first sentence made me cringe. The second I partially agree with. "Following best practices while coding [..] is a good starting point" indeed! But not necessarily with the purpose of writing "well optimized [..] code".

The problem with the first sentence is that it preaches premature optimization which is almost always worse than no optimization at all. Regardless of the experience level of a developer, optimizing early, without clear performance benchmarks is wasted time at best.

When it comes to optimization, here's a list of DOs and DON'Ts:

  • DO use a profiler
  • DO measure/test often
  • DO optimize when necessary
  • DON'T blindly optimize code as you're writing it

Then the blog post goes on to list 15 tips to follow in order to get more efficient PHP scripts. The first few are generally harmless but the second half of the list is filled with gems that have a huge potential to hurt you in the long run if miss-used. Recommendations such as the following are a sure recipe for pain:

  • Create Classes Only When it's Required
  • Disable Debugging Messages
  • Use Methods in Derived Classes
  • If you are bound to have XML form of data, then use regular expression to parse it instead of DOM manipulation.

is the founder of Donaq, a software development consulting company with a focus on mobility. You can find Mike on Google+ and on LinkedIn.
Design copyright (c) Miky Dinescu