简体   繁体   English

Java Getter方法性能

[英]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. 我正在创建一个游戏,并且我所有的数据都被封装了,这显然意味着如果我想从该类的实例中获取某些东西,则必须调用getter方法。 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. 我必须对同一个getter方法使用多个调用,以便从对象中获取单个字段并对其执行多项操作。 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. 但是,我认为该答案中有关可读性和最佳实践的讨论都误解了OP的问题。 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. 他在问他是否可以/应该创建对检索到的对象的本地引用,而不是在每一行上都调用getter,在我的世界中,这是标准做法,并且确实更具可读性。

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. 第二个版本更具可读性,尤其是在现实世界中,当代码中存在更多噪音和缩进时,读取简短行引用描述性命名的本地var要容易得多,而不是看到相同的getter调用连续十几次。

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. 特别是因为您说您的代码经常被调用,所以JIT将启动。它肯定会看到,可以用更简单的加载代替getter调用。

Don't underestimate the JIT! 不要低估JIT!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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