Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Local reference over instance variable

Tags:

java

libgdx

While going through the libgdx source code for a Stage, I encountered this segment:

public void draw () {
    Camera camera = viewport.getCamera();
    camera.update();

    if (!root.isVisible()) return;

    Batch batch = this.batch;
    if (batch != null) {
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        root.draw(batch, 1);
        batch.end();
    }

    if (debug) drawDebug();
}

(Link on GitHub.)

What interested me was this line: Batch batch = this.batch;

My first guess was some caching improvement. Am I right, or is there another reason to avoid using the instance variable directly?

like image 514
EntangledLoops Avatar asked Feb 06 '15 02:02

EntangledLoops


People also ask

Can a instance variable be reference variable in Java?

Instance variables can be used only via object reference. Class variables can be used through either class name or object reference.

Does Java prioritize usage of instance variables over local variables?

The short answer/advice is don't use instance variables over local variables just because you think they are easier to return values. You are going to make working with your code very very hard if you don't use local variables and instance variables appropriately.

How do you reference an instance variable?

Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference. VariableName.

Can local variable and instance variable have same name?

with Same Name. Although it is usually a bad idea, you can declare a formal parameter or a local variable with the same name as one of the instance variables.


1 Answers

In the early Java days, this was imho sometimes used as an optimization, to avoid accessing a member variable. However nowadays I believe, Hotspot can optimize better than us humans.

However, in this context it might be used to prevent problems in case of concurrent modification of that variable, since begin() and end() are likely required to be called on the same instance.

like image 119
martin Avatar answered Oct 05 '22 23:10

martin