简体   繁体   中英

Java Getter Method Performance

I am creating a game and I have all of my data encapsulated which obviously means if I want to get something from an instance of that class, I have to call a getter method. I have a rendering loop that is being called many times a second. I am having to use multiple calls to the same getter method in order to grab a single field from an object and do multiple things with it. Would it be better to just store an extra reference to the object that I am constantly grabbing in my class that needs it? In this case I could grab it in the constructor and be done. Does this make sense? Thanks a ton.

I agree with the other posted answer that there is no performance difference.

However, I think the discussion in that answer about readability and best practice both misunderstand the OP's question. He is not asking if he can eschew best practice and not use getters. He's asking if he can/should create a local reference to the retrieved object rather than calling the getter on every line, and in my world that is standard practice and is indeed much more readable.

Consider first:

doFooThings(service.getFoo());

doBarThings(service.getFoo().getBar());

doBazThings(service.getFoo().getBar().getBaz());
doMoreBazThings(service.getFoo().getBar().getBaz());
doOneLastAmazingBazThing(service.getFoo().getBar().getBaz());

Compare to:

Foo myFoo = service.getFoo();
doFooThings(myFoo);

Bar myBar = myFoo.getBar();
doBarThings(myBar);

Baz myBaz = myBar.getBaz();
doBazThings(myBaz);
doMoreBazThings(myBaz);
doOneLastAmazingBazThing(myBaz);

The second version is much more readable, especially in the real world when there is a lot more noise and indentation in the code, it is much easier to read terse lines reference local vars that are descriptively named, rather than seeing the same getter call appear a dozen times in row.

Would it be better to just store an extra reference to the object that I am constantly grabbing in my class that needs it?

No.

Especially since you say your code is called often, the JIT will kick in. It will certainly see that the getter call can be replaced by a more simple load.

Don't underestimate the JIT!

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