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)

5
  • I think you answered your own question. Commented Oct 3, 2015 at 20:06
  • 2
    Check the byte code. (2) has one less instruction. Commented Oct 3, 2015 at 20:08
  • @EJP: what if you turn on optimizations? Currently I have no access to a java bytecode viewer. But evidently debug mode results in some sort of one-on-one mapping. Commented Oct 3, 2015 at 20:09
  • 1
    See also: stackoverflow.com/questions/13621324/… Commented Oct 3, 2015 at 20:10
  • 1
    @Commusoft The Java compiler does little or nothing in the way of optimization. Commented Oct 3, 2015 at 20:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@mcw, integers aren't subject to garbage collection, nor the local variables. As for objects - they are created on heap in any case stackoverflow.com/a/27587519/2170192

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.