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

后端 未结 8 2739
醉话见心
醉话见心 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.

提交回复
热议问题