High CPU usage for .NET 1.1 XSL transformation
In .NET 1.1, XSL transformation with System.Xml.XmlDataDocument may run very slowly and the CPU usage may reach 100% if you transform large data.
Repro Code
1. XSL file
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
</tr>
<xsl:for-each select="root/element">
<tr>
<td><xsl:value-of select="value"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
2. C# source code
System.Xml.XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml("<root><element/></root>");
XmlElement root = doc.DocumentElement;
XmlElement e = null;
for(int i = 0; i < 100000; i ++)
{
e = doc.CreateElement("element");
e.InnerXml = "<value>" + i + "</value>";
root.AppendChild(e);
}
XslTransform transform = new XslTransform();
transform.Load("file://c:\\xsl.txt");
StringWriter writer = new StringWriter();
System.Threading.Thread.Sleep(10000);
transform.Transform(doc, null, writer, null);
//Console.Write(writer.ToString());
System.Threading.Thread.Sleep(10000);
Console.Write("finish");
Symptom
If we replace the System.Xml.XmlDataDocument with System.Xml.XmlDocument, the performance is improved significantly. The following two pictures are the CPU usage for the application with the above two classes.
We can see the peak CPU usage is 100%, the XmlDataDocument will keep consuming CPU while the XmlDocument will only reach one peak.
Root Cause
This behavior is by design. The XmlDataDocument class is primarily designed for synchronizing XML with DataSet.
Solution
There are 2 options to resolve this issue:
1. Run XSL transformations by using the XmlDocument or XPathDocument classes instead of XmlDataDocument
2. Upgrade to .NET 2.0 or higher and use XslCompiledTransform Class. Please note, although the performance has improved a lot for XmlDataDocument in .NET 2.0, it is still much slower than XmlDocument or XPathDocument
References
Performance of XSLT Transformations in the .NET Framework:
https://support.microsoft.com/kb/325689
Using the XslCompiledTransform Class:
https://msdn.microsoft.com/en-us/library/0610k0w4.aspx
Best Regards,
Zhixing Lv