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?
Instance variables can be used only via object reference. Class variables can be used through either class name or object reference.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With