XNode Performance Comparison: ToString() VS XNode.DeepEquals()
A few weeks back, I developed an XML message parser and cleaner for Healthcare CDA messages. As part of the project, I needed to do a comparison of two nodes to see if they contained the same content. For the first run, I just called XNode.ToString() on the nodes and performed a string comparison. Everything seemed to work well enough, but the memory consumption was through the roof. I ran a memory profile on my unit test and here were the results.
As you can see, the memory performance awful. The XML document that was processed was decently sized (~1 MB), but I couldn’t believe that the process had ended up consuming over 250 MB of memory. The culprit was clearly the System.Xml.Linq.XNode.ToString() method call.
I did some digging and found the XElement.DeepEquals(). This method will compare the current and any descendant nodes; this includes elements and attributes. I decided to give this method a shot and the results were amazing.
Yep, 96% of the overall memory consumption was eliminated and the overall consumption dropped to just about 10 MB. So, there you have it, if you need to compare XNodes have a good time and do it with DeepEquals.