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

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

    The choice shouldn't really be about performance hit but about code readability.

    When you create a variable you can give it the name it deserves in the current context. When you use a same value more than one time it has surely a real meaning, more than a method name (or worse a chain of methods).
    And it's really better to read:

    String username = user.getName();
    SomeMethod1(a, b, username, c);
    SomeMethod2(b, username, c);
    SomeMethod3(username);
    

    than

    SomeMethod1(a, b, user.getName(), c);
    SomeMethod2(b, user.getName(), c);
    SomeMethod3(user.getName());
    

提交回复
热议问题