7

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?

3
  • Have you stepped through with a debugger? At a guess, maybe something in the if body recurses (and modifies the instance batch reference). Commented Feb 6, 2015 at 2:10
  • See also "avoiding getfield opcode". Commented Feb 6, 2015 at 2:59
  • Good thoughts, but the batch instance reference isn't changed between begin() and end() blocks, and this draw method isn't recursive. Commented Feb 6, 2015 at 3:16

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree this looks like subtle optimization. this.batch is final so it's the only plausible reason. Java SE has stuff like this in it too.
0

That is an interesting bit of code.

One possibility would be to ensure that each of the calls to batch methods are to the same object. If some other code modifies this.batch on another thread, one possible result would be for some of the method calls to be to one instance of a Batch object while the rest of the calls go to another instance of a Batch object.

Another possibility is that some programmers carry over ideas and styles from other languages (in this case a language where you must use an identifier such as "self" to access the current instance) and in this case they may have been trying to avoid typing this.batch repeatedly.

Not knowing more about the code sample, I can only make guesses.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.