[英]What function is more efficient?
我是Java的新手,我想知道这两个函数之间是否有区别:
public static String function1(int x) {
String res = "";
if(x > 10)
res = "a";
else
res = "b";
return res;
}
和:
public static String function2(int x) {
if(x > 10)
return "a";
return "b";
}
我不是在讲代码的长度,而只是在讲效率。
从理论上讲,第二个版本效率更高,反编译为:
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
而带有赋值的版本反编译为:
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
可以看到,该附加变量已创建并返回。
但是实际上,实际运行时性能的差异应该可以忽略不计 。 JIT编译器将(希望)优化无用的变量,并且在任何情况下,除非根据您的探查器,代码位于热代码路径中,否则这肯定会视为过早的优化。
两种版本最终都创建一个字符串"a"
或"b"
并将其返回。 但是版本2在效率方面更好,它不会在内存中创建冗余的空字符串""
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.