Performance: XDocument versus XmlDocument

杀马特。学长 韩版系。学妹 提交于 2019-11-26 21:12:22

问题


I have read a comparison between the two here. This is primarily a question of performance, relating to both memory and speed.

I've got several XML documents that are upwards of 100 - 300 K in size. I've noticed that there is some lag when loading this information into an XDocument rather than an XmlDocument object.

  • Is there a serious performance difference between these two objects?
  • Do they access the content of the XML differently?
  • When working with a string of XML, which is preferred, or is there a difference?

The end use of these object is to run queries (XPath or LINQ, depending) on the object in question.


回答1:


XmlDocument is a purely managed implemenation of the Document Object Model. There is no interop with any COM components, such as the MSXML library. Any claim otherwise is completely bogus. The entire XLinq set of APIs came about as a friendlier way to interact with XML with introduction of LINQ in the .NET Framework.

If you're trying to maximize performance and are comfortable using XPath, try using the XmlDocument and using compiled XPath expressions.




回答2:


XmlReader is the lowest API in .NET which all other XML APIs in .NET use under the scenes. Naturally that means it's the hardest to deal with, as well as fastest. It's a streaming API, so it is best fit for memory as well.

Between XmlDocument and XDocument aka Linq to XML, here are some raw numbers: http://blogs.msdn.com/b/codejunkie/archive/2008/10/08/xmldocument-vs-xelement-performance.aspx

Both of which find XDocument class being faster/more efficient. Programmer productivity/efficiency shouldn't be ignored as well. Personally I find it easier to work with XDocument.




回答3:


I wrote a test fiddle. And it goes like this

var str = "some xml here";
string x = null;

// TEST 1
var el = XElement.Parse(str);

for (int i = 1; i < 1000000; i++)
{
    x = el.Element("EL1NAme").Element("InnerELNAme").Value;
}

Console.WriteLine(x);

// TEST 2
var readerSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null };

XmlDocument doc = new XmlDocument();
using (var xmlReader = XmlTextReader.Create(new System.IO.StringReader(str), readerSettings))
{
    doc.Load(xmlReader);
}

for (int i = 1; i < 1000000; i++)
{
    x = doc.SelectSingleNode("//InnerELNAme").InnerText;
}

Result of this test was that TEST 1 was 10 times faster. So, here XElement outperformed XmlDocument



来源:https://stackoverflow.com/questions/4383919/performance-xdocument-versus-xmldocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!