|
Summary
The "truth" (on MSXML) about which is the faster of or
I have seen a lot of 'debate' over which yields the best performance between <xsl:for-each> and <xsl:apply-templates> - but never yet seen anything but guesses as to which is actually the faster. This article is not designed to be the definitive answer to this question - but just a short examination of the evidence with regard to one parser - MSXML.
So taking the XML shown below let's take two very brief stylesheets that do the same thing but using the two different methods:-
Example A (using <xsl:for-each>):- <?xml version=1.0?> <xsl:stylesheet version=1.0 xmlns:xsl=http://www.w3.org/1999/XSL/Transform> <xsl:template match=/> <xsl:for-each select=root/data> <xsl:value-of select=./> </xsl:for-each> </xsl:template> </xsl:stylesheet>
Example B (using <xsl:apply-templates>):- <?xml version=1.0?> <xsl:stylesheet version=1.0 xmlns:xsl=http://www.w3.org/1999/XSL/Transform> <xsl:template match=/> <xsl:apply-templates select=root/data/> </xsl:template> <xsl:template match=data> <xsl:value-of select=./> </xsl:template> </xsl:stylesheet>
The performance results of these two stylesheets is (MSXML 4 figures in square brackets):- Example A (using <xsl:for-each>) has a 29% [21%] reduction in time taken over Example B (using <xsl:apply-templates>).
This is not a huge difference - and depending on the size of the input XML may have a negligable or massive difference on the overall performance of the stylesheet. Obviously, the processing between the for-each or within the applied template will have a bearing on this performance (as the code would be written in subtely different ways) - but this example demonstrates the raw difference on a simplest example as you might find.
But this is in no way to suggest that we should all stop using applied templates and write everything inside huge for-each loops! Like any programming language we continually make trade-offs between final performance of our programs and the maintainability of those programs. For example, in procedural languages we could write almost all of the code within one enormous procedure - but we don't... because we realise that although the performance might scream along, the job of maintaining a multi-zillion line procedure is a nightmare come true. The same applies to XSLT - applied templates give our code some modularity (it would seem at the expense of a little performance) - and we can use that modularity to make isolated changes to parts of the whole without adversley endangering the reliability of the whole... a stylesheet that works (albeit slightly slower) is far better than one than screams along but gives the wrong results!
Cheers - Marrow http://www.MarrowSoft.com - home of Xselerator (XSLT IDE and debugger) http://www.TopXML.com/Xselerator
| Further additional information | |
Updating comments...
Updating comments...
|