Premature optimization in Java: when to use “x = foo.getX()” vs simply “foo.getX()”

后端 未结 8 2746
醉话见心
醉话见心 2021-02-19 14:40

When I find myself calling the same getter method multiple times, should this be considered a problem? Is it better to [always] assign to a local variable and call only once?

相关标签:
8条回答
  • 2021-02-19 15:30

    I generally store it locally if:

    1. I'm will use it in a loop and I don't want or expect the value to change during the loop.

    2. I'm about to use it in a long line of code or the function & parameters are very long.

    3. I want to rename the variable to better correspond to the task at hand.

    4. Testing indicates a significant performance boost.

    Otherwise I like the ability to get current values and lower level of abstraction of method calls.

    0 讨论(0)
  • 2021-02-19 15:31

    For plain getters - those that just returns a value - HotSpot inlines it in the calling code, so it will be as fast as it can be.

    I, however, have a principle about keeping a statement on a single line, which very often results in expressions like "foo.getBar()" being too long to fit. Then it is more readable - to me - to extract it to a local variable ("Bar bar = foo.getBar()").

    0 讨论(0)
提交回复
热议问题