smhy8187

 

Improving the performance of XslCompiledTransform

Improving the performance of XslCompiledTransform

XSLT转换会带来很大的性能问题,查查资料如果一定要用XSLT,牺牲一些性能可能是避免不了的了,看来只能优化,看来对XSLT  .NET转换要做个全面点的性能测试,不然真的对他没信心!下面是老外写的东东,把对象缓存起来是个可行的解决方案!

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.

posted on 2008-01-24 17:25  new2008  阅读(225)  评论(0)    收藏  举报

导航