Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiling an XPath expression?

Tags:

java

xml

xpath

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?

like image 774
Jjang Avatar asked Apr 26 '26 10:04

Jjang


2 Answers

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.

like image 67
Kninnug Avatar answered Apr 28 '26 00:04

Kninnug


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.

like image 39
creinig Avatar answered Apr 27 '26 23:04

creinig