Joakim Nygård Archive Linked About

Optimizing PHP Through Habits

31 Mar 2007

What has been a long interest of mine in writing simple, maintainable and secure (a.k.a. Good[tm]) code, has forked off the offspring of optimization.

There are nummerous discussions in the blogosphere about whether to use echo versus print, if for() is faster than while(), etc. and though the gains are usually very small, I desided to add my thoughts to the debate.

I found an article on optimization through coding habits in Ilia Alshanetsky’s zend performance slides and decided to test some of the claims. My test machine is my MacBook Pro 1.83GHz w. 2GB RAM, MacOS X 10.4.9, Apache 1.3 and PHP 5.2 (with Xdebug 2.0). I also have lots of applications running.

UPDATE: To summarize, this slow code runs in 500ms (although this time will vary a great deal depending on your error_reporting level):

$rows = array_fill(0, 10000, array('id'=>0));
require_once('foo.php');
for( $i=0; $i < count($rows); $i++) {
	foo::notdeclaredstatic();

	$rows[$i][id] = 0;
}

By using the techniques above, it can be made to complete in 68ms:

$rows = array_fill(0, 10000, array('id'=>0));
function __autoload($classname) { require_once( 'foo.php'); }
$size = count($rows);
for( $i=0; $i < $size; $i++) {
	foo::declaredstatic();

	$rows[$i]['id'] = 0;
}

10000 iterations is a lot for one request to a page. Using the techniques, the code became roughly 7 times faster.

I am not out to prove Ilia wrong - he knows PHP better than most - and for all I know, they could have optimized those very functions in PHP 5.2. I am, however, interested in seeing what can be done to optimize PHP performance simply by doing things differently, by tweaking one’s coding style. It would appear that there are improvements, albeit small, to achieve from minimal effort. Plus I was surprised by the discrepancies I found compared to Ilia’s recommendations.