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?
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.
The second evaluate implicitly compiles the expression as well, but throws away the compiled form immediately after evaluation. In your example this doesn't make any difference, since you use the expression only once.
But if you use the expression more than once, compiling it once and re-using the compiled form multiple times can save a significant amount of processing time compared to re-compiling it every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With