The performance comparison between methods to convert an Xml tree to a string within .NET framework.
In web service enviroment, it is often necessary to convert the Xml tree to a string in order to calculate the hash or digital signature. NET framework provides several classes to parse XML document, each one has its own strength, here we investigate the difference of performance between them on my laptop. XmlUTF8TextReader is created using XmlDictionary.CreateTextReader() method with XmlReader interface. For XElement and XDocument, Time to convert it to String is measured against ToString method instead of ReadOuterXml method. The limitations about ToString method of XElement and XDocument is that they return the string with the spaces and \n which makes tasks which are sensitive to those characters unstable.
|Class.Method||Time to load the Xml Document (ms)||Time to convert it to String (ms)|
It appears that the standard XmlReader.ReadOuterXml is the fastest at the time of writing this blog. Although all the childrens of XmlReader implement ReadOuterXml method, but not all of them are created equally. On average, XmlReader is fastest with 50 ms to read a 1 MB xml file, XmlTextReader is the slowest with 90 ms. XmlUTF8TextReader is in the middle with 79 ms. Other options include indexing the Xml document in XElement or XDocument, then travel to the Xml element of the document and call ToString method to obtain the outer xml. In the above table, we can see that it only takes 35ms for the ToString method of XElement or XDocument to complete the transaction. However, the overhead of creating XElement or XDocument is also significant with 40ms and 46ms each. If ReadOuterXml needs to be called frequently, this approach has the clear advantage.