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.