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

后端 未结 8 2699
醉话见心
醉话见心 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: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()").

提交回复
热议问题