This question came up in the forums a little while ago, and I thought it might be interesting to do some comparisons.
I first came up with a few ways of turning an XmlDocument into an XDocument.
privatestatic XDocument DocumentToXDocument(XmlDocument doc)
private static XDocument DocumentToXDocumentNavigator(XmlDocument doc)
private static XDocument DocumentToXDocumentReader(XmlDocument doc)
return XDocument.Load(new XmlNodeReader(doc));
Next I whipped up a function to time these with something quick and dirty. I make sure the past activity doesn't both much in terms of leaving garbage, and I warm up the action a bit (I also warm up the Stopwatch methods, just in case).
privatestatic long Time(int count, Action action)
for (int i = 0; i < 3; i++)
Stopwatch watch = new Stopwatch();
for (int i = 0; i < count; i++)
long result = watch.ElapsedMilliseconds;
And finally, all together:
StringBuildersb = new StringBuilder();
for (int i = 0; i < 1000; i++)
string text = sb.ToString();
XmlDocument doc = new XmlDocument();
long docToXDoc = Time(1000, () => DocumentToXDocument(doc));
long docToXDocNavigator = Time(1000, () => DocumentToXDocumentNavigator(doc));
long docToXDocReader = Time(1000, () => DocumentToXDocumentReader(doc));
Note that the actual numbers don't matter much, as this is my laptop running a bunch of things in the background, in the debugger and whatnot, but the relative values are interesting to see.
These are the values I got (they vary a bit each run, but not by much).
- Using OuterXml: 1973 ms.
- Using a navigator over the document: 1254 ms.
- Using a reader over the document: 1154 ms.
Not surprisingly, avoiding the creation of a big string just to re-parse it is a big win - save the planet, use less CPU power!