5

Given the following methods:

public int methodOne() {
    int total = local_int_one + local_int_two;
    return total;
}

public int methodTwo() {
    return local_int_one + local_int_two;
}

1) Is the only difference in the above methods readability or is there a micro-optimization "benefit" in methodTwo()?

2) Should the defining of local variables in a narrow scope be shunned and avoided when possible? (I can see methodTwo becoming unreadable if several calculations must be performed in a single statement)

user207421
  • 305,947
  • 44
  • 307
  • 483
VILLAIN bryan
  • 701
  • 5
  • 24

1 Answers1

5

The short answer is: methodTwo() is slightly more efficient.

methodOne() results in the following bytecode:

public int methodOne();
 0  aload_0 [this]
 1  getfield com.example.Test.local_int_one : int [13]
 4  aload_0 [this]
 5  getfield com.example.Test.local_int_two : int [15]
 8  iadd
 9  istore_1 [total]
10  iload_1 [total]
11  ireturn

And here's the bytecode for methodTwo():

public int methodTwo();
 0  aload_0 [this]
 1  getfield com.example.Test.local_int_one : int [13]
 4  aload_0 [this]
 5  getfield com.example.Test.local_int_two : int [15]
 8  iadd
 9  ireturn

But note that this optimization is too minor, and that code readability in this case matters a lot more then a couple of java instructions.

If you think a temporary variable will contribute to code readability, then, by all means, use it.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
  • Almost two years later, I'd like to add a follow-up here if I may. Since methodTwo() does not perform istore_1, does this mean that (in Java) there would be no additional gc step to perform (since the value is just returned and not stored)? ... so in a gc-critical environment, instantiating variables in small scopes should be shunned? – VILLAIN bryan Jun 09 '17 at 17:13
  • 1
    @mcw, integers aren't subject to garbage collection, nor the local variables. As for objects - they are created on heap in any case https://stackoverflow.com/a/27587519/2170192 – Alex Shesterov Jun 13 '17 at 16:53