Why compiling an XPath expression?

java, xml, xpath

Solution

Compiling the XPath expression saves it in a format that can be used immediately. When evaluating the expression is compiled as well but the compiled result is discarded afterwards.

Compiling is recommended when the same expression is used over and over, for example in a loop.

Problem

I have the following two code segments which does the same thing, except one is compiling the expression and one is just evaluating it. ``` //1st option - compile and run //make the XPath object compile the XPath expression XPathExpression expr = xpath.compile("/inventory/book[3]/preceding-sibling::book[1]"); //evaluate the XPath expression Object result = expr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; //print the output System.out.println("1st option:"); for (int i = 0; i < nodes.getLength(); i++) { System.out.println("i: " + i); System.out.println("*******"); System.out.println(nodeToString(nodes.item(i))); System.out.println("*******"); } //2nd option - evaluate an XPath expression without compiling Object result2 = xpath.evaluate("/inventory/book[3]/preceding-sibling::book[1]",doc,XPathConstants.NODESET); System.out.println("2nd option:"); nodes = (NodeList) result2; //print the output for (int i = 0; i < nodes.getLength(); i++) { System.out.println("i: " + i); System.out.println("*******"); System.out.println(nodeToString(nodes.item(i))); System.out.println("*******"); } ``` The output is exactly the same. What is the difference between compiling and just evaluating? Why would I compile/not compile an expression?

Original source