[英]Are multiple calls to the same method in the same statement optimized by the compiler?
Let's say I do something like this in Java 8 (Android specifically) 假设我在Java 8中做了类似的事情(特别是Android)
String name = someObject.getName() != null ? someObject.getName() : "null";
and the method getName()
might have a lot of calls to other methods to resolve the name. 并且方法
getName()
可能会有很多调用其他方法来解析名称。 Also suppose I'm calling this code quite often. 还假设我经常调用这段代码。
Would it be better, performance wise, to do something like this instead? 做这样的事情会更好,性能更好吗?
String name = someObject.getName();
name = name != null ? name : "null";
This looks like an optimization possible, called CSE ; 这看起来像一个可能的优化,称为CSE ; a
JVM
AFAIK does that (but not sure about Android). JVM
AFAIK做到了这一点(但不确定Android)。
But this highly depends on what getName
does, if it allocates internally other objects and does some other things. 但这很大程度上取决于
getName
作用,如果它在内部分配其他对象并做其他一些事情。 Unfortunately I can't even tell how to prove me wrong or right here (might need to investigate); 不幸的是,我甚至无法告诉如何证明我错了或在这里(可能需要调查); honestly I have a habit of doing this myself.
老实说,我有自己这样做的习惯。 For example:
例如:
for(int i=0;i<list.size();++i){
}
I try to always extract the int size = list.size()
before the loop; 我尝试在循环之前总是提取
int size = list.size()
; even if this in my understanding is subject to scalar replacement
optimization. 即使这在我的理解中受到
scalar replacement
优化的影响。
The second version is calling getName
one time, while the first, in case is not null, it's calling that 2 times... so if it is very heavy, the second version is better. 第二个版本是一次调用
getName
,而第一个版本,如果不是null,则调用2次...所以如果它非常重,第二个版本更好。
As Arnaud said, you have to consider if the value can change between the two calls: in this case you will get a performance boost, but a risk to get an "old" value. 正如Arnaud所说,你必须考虑两个调用之间的值是否会发生变化:在这种情况下,你会获得性能提升,但却有获得“旧”值的风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.