且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:使用getter vs缓存值

更新时间:2023-11-28 11:07:28

这完全取决于什么得到了。如果它是一个简单的getter(检索数据成员),那么如果JVM确定代码是性能的热点,那么JVM将能够即时内联它。这实际上是Oracle / Sun的JVM被称为HotSpot的原因。 :-)它将应用积极的JIT优化,它会看到它需要它(当它可以)。但是,如果getter做了一些复杂的事情,那么使用它可能会慢一点,让它重复这个工作。

It depends entirely on what the getter does. If it's a simple getter (retrieving a data member), then the JVM will be able to inline it on-the-fly if it determines that code is a hot spot for performance. This is actually why Oracle/Sun's JVM is called "HotSpot". :-) It will apply aggressive JIT optimization where it sees that it needs it (when it can). If the getter does something complex, though, naturally it could be slower to use it and have it repeat that work.

如果代码不是热点,那么当然,你不关心性能是否有差异。

If the code isn't a hot spot, of course, you don't care whether there's a difference in performance.

有人曾经告诉我,内联的getter有时会比缓存到局部变量的值更快,但我从来没有向自己证明这一点,也不知道为什么会出现这种情况的理论。

Someone once told me that the inlined getter can sometimes be faster than the value cached to a local variable, but I've never proven that to myself and don't know the theory behind why it would be the case.