In a Java environment, which performs better?
a)
public void eventHandler(SomeEvent event) {
event.getPlayer().doThis();
event.getPlayer().doThat();
event.getPlayer().alsoThis();
event.getPlayer().getStats().addStat("foo", 1);
event.getPlayer().getStats().addStat("bar", 1337);
}
b)
public void eventHandler(SomeEvent event) {
Player player = event.getPlayer();
player.doThis();
player.doThat();
player.alsoThis();
PlayerStats stats = player.getStats();
stats.addStat("foo", 1);
stats.addStat("bar", 1337);
}
- The
SomeEvent
class is an immutable snapshot of something that just happend and will always return the same values via its getter-methods - In both scenarios, we will assume that
event
andevent.getPlayer()
are guranteed to never be null. - We will also assume that both
Event#getPlayer()
andPlayer#getStats()
are not performing any calculations, but instead are just returning a referenced object. - Naturally, there could be even more method calls - it's just an example.
By gut feeling, i have so far assumed that option b)
would be consuming less CPU power and therefore more RAM during the execution of the method. And since the environment i usually work in, usually has a higher abundance of RAM and the processes are tied to non-async single-core threads, i have also usually gone with b)
as a habit.
Is there anything to that? Does it even make a significant difference other than maybe a few nanoseconds? Or is there maybe an option c)
i should be going with instead?
P.S.: Yes, i am aware that i may be worrying about negliable performance improvements with this. But if either way does make an even ever so slight difference, i don't see anything wrong with turning it into a habit while writing my code.