Sunday, April 26, 2009

XslCompiledTransform and XslTransform

XslCompiledTransform and XslTransform
The .NET Framework 2.0 provides a new System.Xml.Xsl.XslCompiledTransform XSLT processor class, which is intended to replace the obsoleted XslTransform class. One of the major differences between the two is that while the latter is an XSLT interpreter, the former is a real XSLT compiler, allowing significantly faster execution times.
Sample code
xslt = new XslCompiledTransform();
xslt.Load(xslFile);

Does it mean XslCompiledTransform is always faster? Surprisingly, the answer is not that simple.
After doing some of my experiments, I came to the following conclusion
• If you are using one of the .NET Framework 2.0 XSLT processors (XslTransform or XslCompiledTransform), NGen'ing the System.Data.SqlXml assembly may improve the application start-up time.
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>ngen install "System.Data.SqlXml, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" /nologo
Installing assembly System.Data.SqlXml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Compiling 1 assembly:
Compiling assembly System.Data.SqlXml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ...
System.Data.SqlXml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
• Most of the times XslCompiledTransform.Load is slower than XslTransform.Load. But when you take concern about the over all performance XslCompiledTransform class is 4 times faster as MS says.
• While XslCompiledTransform is a best choice for the "one Load, many Transforms" scenario, it may be slow for the "one Load, one Transform" scenario, especially for very simple XML/XSLT files and when stylesheet templates are executed only few times. In those cases XslTransform may be faster.
• It is important, especially for server applications, to cache an XslCompiledTransform instance if the same stylesheet is likely to be executed again.