PHP: DOMDocument Performance
At Pinacol, I’m writing a web site framework, which includes a templating engine. Currently, for speed, the templates (in a manner similar to Wordpress) are simply PHP scripts that call various rendering functions embedded in the (X)HTML template. This is great for speed, but I got to thinking that I would prefer separating all PHP code from the presentation layer - meaning that templates would be far more abstract. The obvious way to do this is to load templates as a DOMDocument, operating on special template tags which instruct the template engine on what content goes where - in a manner more like Movable Type than Wordpress.
I was pretty reluctant to do this, though, since XML performance in any language is notoriously bad. So, I decided to run a few tests to see how much of a performance hit I would take by switching to DOMDocuments.
My first thought was that it might be possible to parse a template into a DOMDocument, and then serialize the object and cache it to save PHP the work of parsing the template in the future. This turned out to be impossible; as DOMDocument is an internally implemented class, it can’t be serialized. Bummer.
Next, I tested how slow it would be to create a DOMDocument rather than simply calling include() on the template file. First, I timed how long it took to create a thousand DOMDocument objects and parse the template file into them. Then, I timed how long it took to include() the template file a thousand times. The results:
1,000 DOMDocuments: 0.47112607955933 sec
1,000 include() calls: 0.21324110031128 sec
So it seems that DOMDocument is more than twice as slow. While the cost of either operation is negligible, that 121% performance gain could mean the difference between life and death for a high-traffic site. However, this preliminary test is not really all that conclusive - with database calls and suchlike being made, the only way to determine if using DOM templates will really make a meaningful performance hit is to construct such a system and test its performance. I suppose I should go all out with this - testing a variety of pre-existing template engines (such as Smarty) and find a “sweet spot” of performance vs. elegance.
tacone:
Hello. ( note: I am one of the hundreds which downloaded industry )
Why don’t you cache compiled-dom-templates ? At basic level you could cache a string with php inserts (calling your custom functions) and just include the cached view. You only have to build 1:1 relationship beewten your custom tags and your functions.
Check out PEAR for caching routines ( saving cache, checking source freshness against stored cache and so on ).
For most pages, anyway, a good static cache (only for some page parts maybe ?) would be the faster and simpler solution. Lot faster than php itself.
Beside that I don’t consider a templating-engine to be necessary to achieve logic-content separation.
Cheers
November 3, 2006, 7:22 pm