Java Method invocation vs using a variable

前端 未结 14 2432
北海茫月
北海茫月 2020-11-27 02:57

Recently I got into a discussion with my Team lead about using temp variables vs calling getter methods. I was of the opinion for a long time that, if I know that I was goin

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 03:21

    I think that recent versions of the JVM are often sufficiently clever to cache the result of a function call automatically, if some conditions are met. I think the function must have no side effects and reliably return the same result every time it is called. Note that this may or may not be the case for simple getters, depending on what other code in your class is doing to the field values.

    If this is not the case and the called function does significant processing then you would indeed be better of caching its result in a temporary variable. While the overhead of a call may be insignificant, a busy method will eat your lunch if you call it more often than necessary.

    I also practice your style; even if not for performance reasons, I find my code more legible when it isn't full of cascades of function calls.

提交回复
热议问题