Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPathSelectElement vs Descendants

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")
like image 571
Mattias Avatar asked Oct 27 '09 09:10

Mattias


4 Answers

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.

like image 113
Christian Hayter Avatar answered Nov 05 '22 17:11

Christian Hayter


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

like image 5
roufamatic Avatar answered Nov 05 '22 18:11

roufamatic


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.

like image 2
AnthonyWJones Avatar answered Nov 05 '22 17:11

AnthonyWJones


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
like image 2
Igor Pashchuk Avatar answered Nov 05 '22 16:11

Igor Pashchuk