Skip to content

Cory Foy

Organizational agility through intersecting business and technology

Menu
  • FASTER Fridays
  • Mapping Mondays
  • Player Embed
  • Search Videos
  • User Dashboard
  • User Videos
  • Video Category
  • Video Form
  • Video Tag
Menu

Improving the performance of XslCompiledTransform

Posted on December 12, 2006 by Cory Foy

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.

2 thoughts on “Improving the performance of XslCompiledTransform”

  1. Anonymous says:
    February 9, 2007 at 6:42 pm

    excellent!

  2. Krishna.K says:
    March 9, 2007 at 11:31 am

    Thanks for the tip. This helped me a lot.

    Krishna

Comments are closed.

© 2025 Cory Foy | Powered by Superbs Personal Blog theme