You have a profiled opinion of yours recently.
Performance:
Perhaps it was micro-optimization, with which in 1999-2001. there was something interesting in the version prior to 1.2 JVM, and even then I would have questioned it if some serious figures had not been shown otherwise.
Modern JIT implementations will tell you that today your opinion is inappropriate.
Modern compiler implementations make all kinds of optimizations that make you think of such things as a waste of time in Java. JIT just makes it an even more empty problem.
Logic:
In a parallel situation, your two code blocks are not logically equivalent if you want to see the changes, so a local copy will prevent this. Depending on what you want to do, one or other approaches can create very subtle non-deterministic errors that would be very difficult to fix in more complex code.
Especially if what was return was something mutable, unlike String
, which is immutable. Then even a local copy could change, unless you made a deep clone, and very quickly it was not so fast.
Observe correctly , then measure and then optimize what is important if it does not make the code less maintainable.
The JVM will embed any calls to members of the final
instances and delete the method call if there is nothing in the method call but return this.name;
. He knows that there is no logic in the access method and he knows the final
link, so that he knows that he can embed the value because it will not change.
To this end
person.getName() != null && person.getName().equalsIgnoreCase("Einstein")
expressed more correctly as
person != null && "Einstein".equalsIgnoreCase(person.getName())
because there is no way to have a NullPointerException
Refactoring:
Modern IDE refactoring tools remove any arguments about the need to change the code in a bunch of places.