简体   繁体   中英

In Java, do using “shortcut” variables impact performance?

I have the following piece of code:

Player player = (Player)Main.getInstance().getPlayer();
player.setSpeedModifier(keyMap[GLFW_KEY_LEFT_SHIFT] ? 1.8f : 1);
if (keyMap[GLFW_KEY_W]) {
    player.moveForward();
}
if (keyMap[GLFW_KEY_S]) {
    player.moveBackward();
}
player.rotateTowards(getMousePositionInWorld());

I was wondering if the usage of a local variable (For the player) to make the code more readable has any impact on performance or whether it would be optimised during compilation to replace the uses of the variable seeing as it is just a straight copy of another variable. Whilst it is possible to keep the long version in place, I prefer the readability of having the shorter version. I understand that the performance impact if there was any would be miniscule, but was just interested if there would be any whatsoever.

Thanks, -Slendy.

For any modern compiler, this will most likely be optimized away and it will not have any performance implications. The few additional bytes used for storage are well worth the added readability.

consider these 2 pieces of code:

final Player player = (Player)Main.getInstance().getPlayer();
player.callmethod1();
player.callmethod2();

and:

((Player)Main.getInstance().getPlayer()).callmethod1();
((Player)Main.getInstance().getPlayer()).callmethod2();

There are reasons, why first variant is preferable:

  1. First one is more readable, at least because of line length
  2. Java compiler cannot assume that the same object will be returned by Main.getInstance().getPlayer() this is why second variant will actually call getPlayer twice, which could be performance penalty

Apart from the probably unneeded (Player) cast, I even find your version to be superior to having long worms of calls.

IMHO if you need one special object more than once or twice, it is worth to be saved in a local variable.

The local variable will need some bytes on the stack, but on the other hand, several calls are omitted, so your version clearly wins.

Your biggest performance hit will likely be the function lookup of the objects:

(Player)Main.getInstance().getPlayer();

Otherwise, you want to minimize these function calls if possible. In this case, a local var could save CPU, though if you have a global var, it might be a hair faster to use it.

It really depends on how many times this is done in a loop though. Quite likely you will see no difference either way in normal usage. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM