Search code examples
xmlxpathlogical-operatorsshort-circuiting

behavior of AND operation while using with XPath


I have a question about behavior of AND operation while using with XPath. Currently it evaluates each and every condition while searching in the XPath even though the first condition itself fails. This is weird. Isn't it?

There are loads of languages that follow the short circuit behavior while evaluating the logical AND operation.

Why is Xpath so different? OR is there any other way or configurations to tell XPath to behave like any other language?


Solution

  • There's a difference between XPath 1.0 and XPath 2.0 here.

    XPath 1.0 (quoted by @wero) says that the conditions MUST be evaluated in order, and evaluation MUST stop as soon as a condition returns false.

    XPath 2.0 is much more liberal, and allows the conditions to be evaluated in any order or in parallel.

    Why is XPath 2.0 different? Because it's following the tradition of declarative database query languages rather than the tradition of procedural programming languages. In database query languages, re-arranging boolean expressions to make maximum use of indexes is a critical optimization strategy, that can make a difference between a query running in milliseconds and taking hours. Since expressions can't have side-effects in a declarative language, mandating order of execution is really counter-productive.

    When you say "it evaluates each and every condition" your pronoun "it" is not referring to XPath the language, it is referring to a specific XPath implementation. It would be interesting to know (a) which one, and (b) how you observed this behaviour and came to these conclusions.

    UPDATE

    XPath 3.0 and 3.1 are the same as 2.0.

    The draft XPath 4.0 takes a different approach: it says that optimisers can evaluate the expressions in any order they like, but must behave as if they didn't. That is, you can evaluate the second condition before the first if you want (or evaluate them in parallel), but if the first condition evaluates to false then you aren't allowed to throw an error just because evaluation of the second condition failed.