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

后端 未结 8 2692
醉话见心
醉话见心 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:21

    Most of the time I would use getX if it was only once, and create a var for it for all other cases. Often just to save typing.

    With regards to performance, the compiler would probably be able to optimize away most of the overhead, but the possibility of side-effects could force the compiler into more work when doing multiple method-calls.

提交回复
热议问题