Home > Net >  Caching java instance for peformance
Caching java instance for peformance

Time:02-01

Please assist, What is meant by caching this line/new instance in java for example:

XPath xpath = XPathFactory.newInstance().newXPath();

I know I have to store insome sort of memory... may someone show me an example.

Thanks.

CodePudding user response:

Caching means don't let the garbage collector trashing your variable after you use it, if you already know that you will need to use the same variable a bit later (but the GC does not understand that).

It really depends on how long does the Xpath states last (may be function-scope, instance-scope or class-scope - or even a more reduced scope like a for loop or an if block, but that's only you knowing it).

The below should help to understand:

Case 1 - inside a function

If you do this:

public Object doSomething() {
    //code...
    XPath xpath = XPathFactory.newInstance().newXPath();
    //code...
}

..then the garbage collector will think that once you're out of the function you don't need it anymore and so, it will trash it short after. Next time you call the function again, you will have to rebuild it from scratch.

Case 2 - as a class field

If you instead do this:

public class YourClass {
    
    private final XPath xpath = XPathFactory.newInstance().newXPath();

    public Object doSomething() {
        //code...
        this.xpath.use(...);
        //code...
    }

.. then you're doing the job only once per instance created. If you create 10 instances of your class, you'll do it 10 times. If you create just one, you'll do it just once. And the garbage collector will preserve the value of each instance as long as that instance exists.

Case 3 - static field

But if this really never depends on anything, then it should be static:

public class YourClass {
    private static final XPath XPATH = XPathFactory.newInstance().newXPath();
    
    public Object doSomething() {
        //code...
        XPATH.use(...);
        //code...
    }        
}

... in this last case, no matter how many instances of the class you build, you'll always have one and only one instance of Xpath, and the garbage collector will let the variable live in peace as long as one instance of your class exists somewhere

CodePudding user response:

Suppose the code with the line above is called from a loop:

void bar() {
 for (int i = 0; i < 10; i  ) {
   XPath xpath = XPathFactory.newInstance().newXPath();
   // use xpath variable
  }
}

Here 10 instances of XPath are created. Alternatively you can hoist xpath variable declaration out of the loop so only 1 instance will be created:

void bar() {
 XPath xpath = XPathFactory.newInstance().newXPath();
 for (int i = 0; i < 10; i  ) {
   // use xpath variable
  }
}

This is the simplest case of caching, i.e. reusing some resource instead of recreating it.

  •  Tags:  
  • Related