Accessor Method Performance and Optimization

前端 未结 6 2400
有刺的猬
有刺的猬 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:47

    It is certainly a lot more readable if you put the value in a local variable, which is why you should do it and not because it performs better.

    Another massive difference is if getName() has a side effect (which it shouldn't have but you can't trust other classes blindly), or if you're working in a multi-threaded system. In the first case the difference is obvious, in the second case another thread might change the value getName() returns while you're executing your statement.

    In both cases what you probably want is to only invoke getName() once.

提交回复
热议问题