2

I wonder if these two methods has any difference.

private int getSum(int a, int b) {
    int total = a + b;
    return total;
}

private int getSum2(int a, int b) {
    return a+b;
}

What I have learned is that a compiler or interpreter will automatically optimize this. Is it right?

Sunil
  • 3,404
  • 10
  • 23
  • 31
John
  • 1,139
  • 3
  • 16
  • 33

1 Answers1

1

This difference will exist in the byte code and it’s impact is, of course, implementation dependent.

Your additional int variable can’t use the space of another variable with disjunct scope, so when executed (interpreted) literally, it raises the required size of the stack frame by four bytes. However, environments like the widely used HotSpot JVM pre-allocate the entire stack space of a thread when it is started and do not support resizing, so with this implementation, the local variable has no impact on the memory consumption at all.

You could be tempted to say, that if you add a local variable to a recursive method, the additional required memory may add up, reducing the maximum recursion depth by a few invocations (in interpreted mode), but as discussed in this answer, there is already an indeterminism in the maximum recursion depth larger than that.

That answer also demonstrates the impact of compilation/optimization on the required stack trace, reducing the required stack space by factor six in the example. When your method is a hot spot, the optimizer will have look at it and one of the tools in its box is a transformation into the SSA form, which only knows variables, which are used to model the data transfers. In other words, the differences between these variants are already eliminated in the intermediate representation. From there, the values are likely mapped to CPU registers when generating the native code, so the result will not require stack space at all.

Though it is even likelier that such a small method gets inlined into the caller each time where the operation gets fused with whatever the caller does, to result in code we can’t predict by just looking at the method. In either case, whether you use a temporary local variable or not, is irrelevant.

Holger
  • 285,553
  • 42
  • 434
  • 765