Java Local reference over instance variable
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?
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.
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.
链接地址: http://www.djcxy.com/p/24668.html上一篇: 斯卡拉期货回调地狱
下一篇: 通过实例变量的Java本地引用