Reputation: 1792
I have a question concerning performance issues when using XPath.
Which one is better and why? (in case of performance of course):
//A/B/C[@id="x"]/../..
vs.
//A[B/C[@id="x"]]
Upvotes: 2
Views: 3469
Reputation: 4393
If anything, you'll get hit on performance by using //
... it is likely that the processor is not going to optimize such an expression and will waste time looking for A
elements as a descendent of C
elements because you are asking it to. I highlight this in the classroom as one of the most common sources of poor performance in XSLT processing (and I cringe every time I see it being abused in StackOverflow questions, but I would spend all day talking about it because it is used so often).
As for the difference between A/B/C[@id='x']/../..
and A[B/C[@id="x"]]
, it depends if the processor rewrites the former into the latter as part of optimization (since it is declarative).
If no such optimization happens, the former will be slower than the latter because the former is asking the processor to take the time to collect all C
elements and walk backup up the tree unioning the grandparent element of each one. Whereas the latter expression uses a predicate that is a boolean true()/false() test of a data-type that is a node set, and the processor knows that the boolean value returned is true() at the first detection of such a C
element and doesn't need to look for any other C
elements (and shouldn't be looking for any other C
elements).
Upvotes: 7