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