Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java optimization : local variable or function call

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.

like image 354
Adrien Gorrell Avatar asked Oct 03 '12 09:10

Adrien Gorrell


1 Answers

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 if getInstructions() may have different results over time.

like image 195
Tomasz Nurkiewicz Avatar answered Nov 15 '22 11:11

Tomasz Nurkiewicz