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?

Radiodef
  • 37,180
  • 14
  • 90
  • 125
EntangledLoops
  • 1,951
  • 1
  • 23
  • 36
  • Have you stepped through with a debugger? At a guess, maybe something in the if body recurses (and modifies the instance `batch` reference). – Elliott Frisch Feb 06 '15 at 02:10
  • See also ["avoiding getfield opcode"](http://stackoverflow.com/questions/4761681/avoiding-getfield-opcode). – Radiodef Feb 06 '15 at 02:59
  • Good thoughts, but the batch instance reference isn't changed between `begin()` and `end()` blocks, and this draw method isn't recursive. – EntangledLoops Feb 06 '15 at 03:16

2 Answers2

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.

Community
  • 1
  • 1
martin
  • 1,185
  • 17
  • 22
  • 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. – Radiodef Feb 06 '15 at 02:56
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.

Simon G
  • 36
  • 2