Which would you do ?
doThings(folder.getInstructions()) ;
for (Instruction instruction : folder.getInstructions()) {
// do things
}
functionCall(folder.getInstructions()) ;
Or this :
instructions = folder.getInstructions() ;
doThings(instructions)
for (Instruction instruction : instructions) {
// do things
}
functionCall(instructions) ;
Above all, I would like to know when it is more efficient to store a value in a local variable, and when it is better to make function calls.
More readable is more efficient. Temporary expressions and local variables need the same space and from CPU/JVM perspective it doesn’t make much difference. JVM will do a better job optimizing/inling it.
However if
getInstructions()method call is expensive, cache it in local variable. If it’s just a plain getter, it will be inlined anyway. Also IMHO in your particular case local variable is more readable and maybe even more correct ifgetInstructions()may have different results over time.