XPathSelectElement vs Descendants

烂漫一生 提交于 2019-12-10 12:48:51

问题


I was wondering if there are any performance differences when using simple queries as:

var x = document.XPathSelectElement("actors/actor")

vs

var x = document.Descendants("actors").Descendants("actor")

回答1:


Note that this

var x = document.Elements("actors").Elements("actor").FirstOrDefault();

is the equivalent of your first statement.

There will be a performance difference, because the methods are doing very different things under the hood. However, optimising purely in-memory operations is a bit pointless unless you are dealing with a large data set. If you are dealing with a large data set, then you should measure the performance of both alternatives rather than trying to predict which one will run faster.




回答2:


Seems like there is a hit, somebody else has done the benchmarking legwork: http://blog.dreamlabsolutions.com/post/2008/12/04/LINQ-to-XML-and-LINQ-to-XML-with-XPath-performance-review.aspx




回答3:


Yes there will be although the two lines aren't equivalent.

The XPath needs to be parsed ultimately into a LINQ expression which would then do this:-

var x = document.Elements("actors").Elements("actor");

However its quite possible that internally a compiled version of the XPath expression is stored so that using an XPath only costs the time it takes to look up the string in some internally held dictionary. Whether that is actually the case or not I don't know.




回答4:


From my limited testing, performance seems very similar. I took a sample XML message from http://msdn.microsoft.com/en-us/library/windows/desktop/ms762271(v=vs.85).aspx

XPath:

/book[id='bk109']

LINQ query:

from bookElement in xmlElement.Descendants( "book" )
where bookElement.Attribute( "id" ).Value == "bk109"
select bookElement

I then executed each 10,000 times (excluding the time it took to parse the string and the first run to eliminate the CLR noise).

Results (100,000 iterations)

  • XPath on XElement: 60.7 ms
  • LINQ to XML on XElement: 85.6 ms
  • XPath on XPathDocument: 43.7 ms

So, it seems that at least in some scenarios XPath evaluation on XElement performs better than LINQ to XML. XPath evaluations on XPathDocument are even faster.

But, it appears that loading an XPathDocument takes a little longer than loading an XDocument (1000 iterations):

  • Time to load XPathDocument: 92.3 ms
  • Time to load XDocument: 81.0 ms


来源:https://stackoverflow.com/questions/1629596/xpathselectelement-vs-descendants

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