Java Local reference to instance variable

Looking through the libgdx source code for Stage , I came across 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 to GitHub .)

I was interested in this line: Batch batch = this.batch;

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

+7
java libgdx
source share
2 answers

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

However, in this context, it can be used to prevent problems if this variable is modified at the same time, since begin() and end() should probably be called in the same instance.

+3
source share

This is an interesting bit of code.

One possibility is to ensure that each of the calls to the batch methods is the same object. If some other code modifies this.batch in a different thread, one of the possible results could be to call some methods on one instance of the Batch object, while the rest of the calls go to another instance of the batch object.

Another possibility is that some programmers transfer ideas and styles from other languages ​​(in this case, a language where you must use an identifier such as "I" to access the current instance), in which case they may have tried to avoid retype this.batch.

Without knowing more about the sample code, I can only guess.

0
source share

All Articles