Accessor Method Performance and Optimization

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

    There is no performance difference. If there is, it's trivially small.

    More importantly, the two code samples actually behave entirely differently in the presence of multiple threads.

    Say that halfway through, someone calls setName and changes the name. Now your code is going through an entirely unexpected path! This has actually been the root cause of a couple historical (even kernel-level) security vulnerabilities.

    Note that I am not advocating blindly copying all results you get into local variables. I'm just pointing out a potential pitfall.

提交回复
热议问题