有两种类型if
java 中的语句 - 经典:if {} else {}
和简写:exp ? value1 : value2
。一个比另一个快还是它们相同?
陈述:
int x;
if (expression) {
x = 1;
} else {
x = 2;
}
三元运算符:
int x = (expression) ? 1 : 2;
那里只有一种类型的“if”语句。另一种是条件表达式。至于哪个性能更好:它们可以编译为相同的字节码,并且我希望它们的行为相同 - 或者如此接近,以至于您绝对不想在性能方面选择一个而不是另一个。
有时一个if
语句会更具可读性,有时条件运算符会更具可读性。特别是,当两个操作数简单且无副作用时,我建议使用条件运算符,而如果两个分支的主要目的is他们的副作用,我可能会使用if
陈述。
这是示例程序和字节码:
public class Test {
public static void main(String[] args) {
int x;
if (args.length > 0) {
x = 1;
} else {
x = 2;
}
}
public static void main2(String[] args) {
int x = (args.length > 0) ? 1 : 2;
}
}
字节码反编译为javap -c Test
:
public class Test extends java.lang.Object {
public Test();
Code:
0: aload_0
1: invokespecial #1
4: return
public static void main(java.lang.String[]
Code:
0: aload_0
1: arraylength
2: ifle 10
5: iconst_1
6: istore_1
7: goto 12
10: iconst_2
11: istore_1
12: return
public static void main2(java.lang.String[
Code:
0: aload_0
1: arraylength
2: ifle 9
5: iconst_1
6: goto 10
9: iconst_2
10: istore_1
11: return
}
正如你所看到的,有一个slight这里字节码的差异 - 是否istore_1
无论是否在支架内发生(与我之前有巨大缺陷的尝试不同:),但如果 JITter 最终得到不同的本机代码,我会感到非常惊讶。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)