我是Java新手,我想知道这两个函数之间是否存在差异:
public static String function1(int x) {
String res = "";
if(x > 10)
res = "a";
else
res = "b";
return res;
}
Run Code Online (Sandbox Code Playgroud)
和:
public static String function2(int x) {
if(x > 10)
return "a";
return "b";
}
Run Code Online (Sandbox Code Playgroud)
而且我不是在谈论代码的长度,而是说效率.
理论上第二个版本更有效,反编译为:
public static java.lang.String function1(int);
Code:
0: ldc #2 // String
2: astore_1
3: iload_0
4: bipush 10
6: if_icmple 12
9: ldc #3 // String a
11: areturn
12: ldc #4 // String b
14: areturn
Run Code Online (Sandbox Code Playgroud)
而具有赋值的版本反编译为:
public static java.lang.String function1(int);
Code:
0: ldc #2 // String
2: astore_1
3: iload_0
4: bipush 10
6: if_icmple 15
9: ldc #3 // String a
11: astore_1
12: goto 18
15: ldc #4 // String b
17: astore_1
18: aload_1
19: areturn
Run Code Online (Sandbox Code Playgroud)
可以看出创建并返回了附加变量.
但实际上,实际运行时性能的差异应该可以忽略不计.JIT编译器(希望)优化掉无用变量,并且在任何情况下,除非代码根据您的分析器处于热代码路径中,否则这肯定会被视为过早优化.
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |