manmal
manmal

Reputation: 3928

XPath: / quicker than //?

If I got it right, / means that the node right to it must be an immediate child of the node left to it, e.g. /ul/li returns li items which are immediate children of a ul item which is the document root. //ul//li returns li items which are descendants of any ul item which is somewhere in the document.

Now: Is /ul/li faster than //ul//li, even if the result set is the same?

Upvotes: 2

Views: 134

Answers (2)

Michael Kay
Michael Kay

Reputation: 163322

There are probably at least 50 implementations of XPath, and their performance varies dramatically, by several orders of magnitude. It's therefore meaningless to ask questions about XPath performance without reference to a specific implementation.

Generally the advice given is to use as specific a path as you can: /a/b/c/d is better than //d. However, this advice is not always correct. Some products will execute //d faster because they have gone to the trouble of creating an index: this is particularly true if you are running against an XML database. Also, performance isn't everything. When you are dealing with complex vocabularies like FpML, the specific path to an element can easily be ten steps with names averaging 20 characters, so that's a 200-character XPath, and it can be very hard to spot when you get it wrong. Programmer performance matters more than machine performance.

Upvotes: 2

Francis Avila
Francis Avila

Reputation: 31621

Generally speaking, yes, of course!

/ul/li visits at most (number_of_ul * number_of_li nodes), with a maximum depth of 2. //ul//li could potentially visit every node in the document.

However, you may be using a document system with some kind of indexing, or you could have a document where the same number of nodes ends up getting visited, or whatever, which could either make // not as slow or or the same speed as or possibly even faster than /ul/li. I guess you could also potentially have a super-dumb XPath implementation that visits every node anyway.

You should profile your specific scenario rather than ask which is faster. "It depends" is the answer.

Upvotes: 3

Related Questions