Java:使用getter vs缓存值 [英] Java: Use getter vs caching value

查看:111
本文介绍了Java:使用getter vs缓存值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回String的getter,我将它与其他String进行比较。我检查null的返回值,所以我的 if 语句看起来像这样(如果是真的话我真的会提前退出)

I have a getter that returns a String and I am comparing it to some other String. I check the returned value for null so my ifstatement looks like this (and I really do exit early if it is true)

if (someObject.getFoo() != null && someObject.getFoo().equals(someOtherString)) {
  return;
}

Performancewise,存储返回的String而不是调用getter会更好吗?这样两次?它甚至重要吗?

Performancewise, would it be better to store the returned String rather than calling the getter twice like this? Does it even matter?

String foo = someObject.getFoo();
if (foo != null && foo.equals(someOtherString)) {
  return;
}






回答问题注释,这个检查不经常执行,并且getter非常简单。我很好奇如何分配一个新的局部变量与另外一次执行getter相比。


To answer questions from the comments, this check is not performed very often and the getter is fairly simple. I am mostly curious how allocating a new local variable compares to executing the getter an additional time.

推荐答案

这完全取决于什么得到了。如果它是一个简单的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.

这篇关于Java:使用getter vs缓存值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆