给出以下方法:
public int methodOne() {
int total = local_int_one + local_int_two;
return total;
}
public int methodTwo() {
return local_int_one + local_int_two;
}
Run Code Online (Sandbox Code Playgroud)
1)上述方法的唯一区别是可读性还是methodTwo()中存在微优化"好处"?
2)是否应该避免在狭窄范围内定义局部变量并尽可能避免?(如果必须在一个语句中执行多次计算,我可以看到方法变得不可读)
简短的回答是:methodTwo()是略微更有效.
methodOne() 得到以下字节码:
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
Run Code Online (Sandbox Code Playgroud)
这是字节码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
Run Code Online (Sandbox Code Playgroud)
但请注意,这种优化太小了,在这种情况下,代码可读性比几条java指令要重要得多.
如果您认为临时变量将有助于代码可读性,那么,无论如何都要使用它.