Calling getters on an object vs. storing it as a local variable (memory footprint, performance)

后端 未结 6 455
庸人自扰
庸人自扰 2020-11-28 06:25

In the following piece of code we make a call listType.getDescription() twice:

for (ListType listType: this.listTypeManager.getSelectableListTyp         


        
6条回答
  •  星月不相逢
    2020-11-28 07:07

    In the context of imperative languages, the value returned by a function call cannot be memoized (See http://en.m.wikipedia.org/wiki/Memoization) because there is no guarantee that the function has no side effect. Accordingly, your strategy does indeed avoid a function call at the expense of allocating a temporary variable to store a reference to the value returned by the function call. In addition to being slightly more efficient (which does not really matter unless the function is called many times in a loop), I would opt for your style due to better code readability.

提交回复
热议问题