views:

363

answers:

2

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")
A: 

Note that this

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

is the equivalent of your first statement.

There will be a performance difference, because the methods are doing different things. However, it will be so miniscule that you don't need to worry about it most of the time.

EDIT: I have no evidence for the above assertion, I'm just going on the principle that optimising 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.

Christian Hayter
Ah, thats right.Exactly what i needed to know. Thanks!
Mattias
except he works with huge xml files (like 1gig or bigger) - then he might want to do a benchmark (he should have a look at how to write a correct microbenchmark: http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java)
@Christian: Is there any evidence that using XPathSelectElement has a "miniscule" performance difference. I'm not saying that it is not true but how is this known. The only way it could be miniscule is if the resulting XPath expression is compiled and cached. That is true of XPath in the System.Xml but is it the same in Linq-To-Xml? Is there some documentation or MS Team blog or some comparison tests posted on the web that bears this out?
AnthonyWJones
@rebugger: The larger the actual search operation the less significant the differences between the two approaches will be. There is no actual XPath search, only a parse of XPath to an equivalent LINQ-To-Xml expression. Of course if this code is run in a loop driven by the large XML then certainly the XPath approach would be slower.
AnthonyWJones
A: 

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.

AnthonyWJones