Improve performace: check your loops
Before I start
I’ve always stayed away from writing a performance topic. There seems to be a lot of performance enthusiasts, benchmarking anything they can, in order to scoop off a few more percent of performance time. To my opinion, if your system is already reacting within an acceptable fashion, there is no need to try to further improve performance. Maintainability is a much more important topic to look at, at that point.
Finding out what is the problem
So you have a script which is not performing the way you want to. The first thing you should do it try to find out what the problem is. There are some tools out there that can help you. If you’re using Zend Studio, there is a profiler which shows you a tree of files and functions with the amount of processing time. (Warning: With Zend Studio 5, you need to close your project and all open files, otherwise you’ll get incorrect values). There is also a profiler in XDebug, which is a bit harder to set up, but works just as well (or even a bit better actually).
If you don’t have the option to install any of these tools, you can echo (or use FirePHP to output) the execution times, using the following script:
$_ENV['exec_start_time'] = microtime(true); .... echo "<!-- ", "After doing XYZ: ", (microtime(true) - $_ENV['exec_start_time']) * 1000, " ms", " -->\n" .... echo "<!-- ", "After doing SOMETHING: ", (microtime(true) - $_ENV['exec_start_time']) * 1000, " ms", " -->\n"
Most likely the problem will be one of these three (in order of likeliness):
- A slow database query. Solving this is outside the scope of this article, but read this PDF about Query tuning for starters.
- To much is executed within a loop and/or the number of items for the loop is to big. Read the rest of the article.
- To much code is executed. This is probably cause of an abstraction layer that is simply to big or of to many abstraction layers. Try to do some refactoring, removing unnecessary abstraction or bypass abstraction on bottleneck positions.
24 Jan 2008 Arnold Daniels 12 comments




