Are multiple calls to the same method in the same statement optimized by the compiler?

Magnus W :

Let's say I do something like this in Java 8 (Android specifically)

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. 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";
Eugene :

This looks like an optimization possible, called CSE; a JVM AFAIK does that (but not sure about Android).

But this highly depends on what getName does, if it allocates internally other objects and does some other things. 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; even if this in my understanding is subject to scalar replacement optimization.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92156&siteId=1