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)
So, by using a local variable you decrease the dependencies between your components, i.e. you decrease the complexity of your code. You should only use global variable when you really need to share data, but each variable should always be visible in the smallest scope possible.
For example: for(int i=0;i<=5;i++){……} In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.
Constants, global variables, class variables, instance variables, and local variables.
A local variable is a type of variable that can be used where the scope and extent of the variable is within the method or statement block in which it is declared. It is used as an iteration variable in the foreach statement, exception variable in the specific-catch clause and resource variable in the using statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With