2

One thing I mostly follow when writing code is if I see some object-attribute or method is being accessed multiple times within the same method, I tend to assign it to a variable and re-use it everywhere.

List<ItemA> itemAList = alpha.doX(..., ..., ...)
              .peek(item -> packagedItems.put(item.getName(), ...))
              .peek(item -> readyItems.put(item.getName(), ..., ...)))
              .map(item -> transform(item.getName(), ...))
              .collect(toList());

As we can see item.getName() has been used multiple times. I would usually move it to a variable and re-use it:

String itemName = item.getName();
List<ItemA> itemAList = alpha.doX(..., ..., ...)
              .peek(item -> packagedItems.put(itemName, ...))
              .peek(item -> readyItems.put(itemName, ..., ...)))
              .map(item -> transform(itemName, ...))
              .collect(toList());

I would sometimes suggest the same in code-reviews as well. However, I would like to now if there are any performance cost with having to de-reference from the object instance over directly being able to access from a variable?

What are some of the thoughts around this practice? And in what circumstances (if any) one would be preferred over the other?

Thank you.

Shabirmean
  • 2,341
  • 4
  • 21
  • 34
  • 1
    the two code snippet you posted are have different semantics. In fact, the second version should not even compile, stating the variable `item` already being defined. Even if it were to compile `item -> ...(item.getName)...` is a lambda function and thus not equivalent to `item -> ...(itemName)...`. – Turing85 Dec 30 '19 at 16:00

1 Answers1

0

(Ignoring the errors in your second code, item is already in use.)

The compiler may inline when a method is final as it's up to the compiler to determine whether the method is "simple" enough for inlining. Getters and setters are usually simple enough to get inlined.

If not the JIT will most likely inline the getters sooner or later at runtime, so either ways item.getName() will be replaced by item.name

Not much of a performance concern.

Adwait Kumar
  • 1,552
  • 10
  • 25
  • One shouldn't rely on the JIT inlining the method. If the getter is not called too often, it won't be inlined. (it's worth noting that you can configure the threshold when a method is considered 'hot'). Also, if a class has any classes that inherit from it, its non-final methods aren't candidates for inlining. – Pateman Dec 30 '19 at 17:31