In .NET 2.0, people may have noticed that the new recommended way of doing XSL transformations is now System.Xml.Xsl.XslCompiledTransform
. And they may be tempted to do something like the following:
public string Transform(string xml, string xsl)
{
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Xml.Xsl.XslCompiledTransform t =
new System.Xml.Xsl.XslCompiledTransform();
XmlReaderSettings settings = new XmlReaderSettings();
XmlReader xmlReader = XmlReader.Create(new System.IO.StringReader(xml));
XmlReader xslReader = XmlReader.Create(new System.IO.StringReader(xsl));
t.Load(xslReader);
t.Transform(xmlReader, null, writer);
return writer.ToString();
}
which is all well and good for on the fly. But there is something tricky going on here. XslCompiledTransform does more than just transform. It compiles the XSLT to MSIL code.
What does this mean? Well, that doing the above is like JITing your ASPX pages – you are incurring the overhead of the transformation and the compilation. Since most people really don’t need to pass in the XSL, you can greatly improve performance by caching the XSL object, or making it static, ala:
private static string myXsl = "
private static System.Xml.Xsl.XslCompiledTransform transformer =
new System.Xml.Xsl.XslCompiledTransform();
static Transform
{
XmlReader xslReader = XmlReader.Create(new System.IO.StringReader(xsl));
transformer.Load(xslReader);
}
In a test, running the first version 1000 times took about 5 seconds. In the second, it took less than a second.
excellent!
Thanks for the tip. This helped me a lot.
Krishna