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

后端 未结 6 448
庸人自扰
庸人自扰 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条回答
  •  萌比男神i
    2020-11-28 07:12

    I'd nearly always prefer the local variable solution.

    Memory footprint

    A single local variable costs 4 or 8 bytes. It's a reference and there's no recursion, so let's ignore it.

    Performance

    If this is a simple getter, the JVM can memoize it itself, so there's no difference. If it's a expensive call which can't be optimized, memoizing manually makes it faster.

    Readability

    Follow the DRY principle. In your case it hardly matters as the local variable name is character-wise as about as long as the method call, but for anything more complicated, it's readability as you don't have to find the 10 differences between the two expressions. If you know they're the same, so make it clear using the local variable.

    Correctness

    Imagine your SelectItem does not accept nulls and your program is multithreaded. The value of listType.getDescription() can change in the meantime and you're toasted.

    Debugging

    Having a local variable containing an interesting value is an advantage.


    The only thing to win by omitting the local variable is saving one line. So I'd do it only in cases when it really doesn't matter:

    • very short expression
    • no possible concurrent modification
    • simple private final getter

提交回复
热议问题