Short answer: methodTwo() bit 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 is 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 small, and this readability of the code in this case is much more important than a few java instructions.
If you think that a temporary variable will make the code easier to read, then by all means, use it.
source share