Accessor Method Performance and Optimization

前端 未结 6 2395
有刺的猬
有刺的猬 2021-02-15 12:11

Often, I come across code where the Getter method is repeatedly used/abused to get some value or pass it as a method parameter, for ex:

public c         


        
6条回答
  •  盖世英雄少女心
    2021-02-15 12:52

    Have you profiled your opinion lately.

    Performance:

    This might have been a micro-optimization that was something to be concerned with in 1999-2001 in a pre-1.2 JVM and even then I would have questioned it unless some serious numbers showed otherwise.

    Modern JIT implementations would tell you that today that your opinion is out of place.

    Modern compiler implementations do all kinds of optimizations that make thinking about things like this a waste of time in Java. The JIT just makes it even more of a waste of concern.

    Logic:

    In a concurrent situation, your two code blocks are not logically equivalent, if you want to see changes, making the local copy will prevent that. Depending on what you want to do, one or the other approaches could create very subtle non-deterministic bugs that would be very hard to pin down in more complicated code.

    Especially if what was return was something mutable unlike a String which is immutable. Then even the local copy could be changing, unless you did a deep clone, and that gets really easy to get wrong really quickly.

    Concern yourself with doing it correctly, then measure and then optimize what is important as long as it doesn't make the code less maintainable.

    The JVM will inline any calls to final instance members and remove the method call if there is nothing in the method call other than the return this.name; It knows that there is not logic in the accessor method and it knows the reference is final so it knows it can inline the value because it will not be changing.

    To that end

    person.getName() != null && person.getName().equalsIgnoreCase("Einstein") 
    

    is expressed more correctly as

    person != null && "Einstein".equalsIgnoreCase(person.getName())
    

    because there is no chance of having a NullPointerException

    Refactoring:

    Modern IDE refactoring tools remove any arguments about having to change code in a bunch of places as well.

提交回复
热议问题