java 中有两种类型的
if
语句 - 经典:if {} else {}
和简写:exp ? value1 : value2
。一个比另一个快还是相同?
声明:
int x;
if (expression) {
x = 1;
} else {
x = 2;
}
三元运算符:
int x = (expression) ? 1 : 2;
那里只有一种类型的“if”语句。另一种是条件表达式。至于哪个性能更好:它们可以编译为相同的字节码,并且我希望它们的行为相同 - 或者如此接近,以至于您绝对不想在性能方面选择一个而不是另一个。
有时
if
语句会更具可读性,有时条件运算符会更具可读性。特别是,当两个操作数简单且无副作用时,我建议使用条件运算符,而如果两个分支的主要目的是它们的副作用,我可能会使用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
}
正如你所看到的,这里的字节码有一个轻微的差异——无论
istore_1
是否出现在支撑中(与我之前有巨大缺陷的尝试不同:),但如果抖动最终以以下方式结束,我会感到非常惊讶不同的本机代码。
您的两个示例可能会编译为相同或几乎相同的字节码,因此性能应该没有差异。
如果执行速度存在差异,您仍然应该使用最惯用的版本(第二个版本用于基于简单条件和两个简单子表达式分配单个变量,第一个版本用于执行更复杂的操作)操作或不适合单行的操作)。
这些是一样的。 它们都相当快,通常约为 10-30 纳秒。 (取决于使用模式)这个时间范围对您来说重要吗?
你应该做你认为最清楚的事情。
只是添加到所有其他答案:
第二个表达式通常称为三元/三元运算符/语句。它非常有用,因为它返回一个表达式。有时,它使典型的简短语句的代码更加清晰。
都不是 - 它们将被编译为相同的。
三元运算符比 if-else 条件更快。
public class TerinaryTest {
public static void main(String[] args)
{
int j = 2,i = 0;
Date d1 = new Date();
for(long l=1;l<100000000;l++)
if(i==1) j=1;
else j=0;
Date d2 = new Date();
for(long l=1;l<100000000;l++)
j=i==1?1:0;
Date d3 = new Date();
System.out.println("Time for if-else: " + (d2.getTime()-d1.getTime()));
System.out.println("Time for ternary: " + (d3.getTime()-d2.getTime()));
}
}
测试结果:
踪迹-1:
if-else 时间:63
三元时间:31
小径2:
if-else 时间:78
三元时间:47
踪迹 3:
if-else 时间:94
三元时间:31
小径 4:
if-else 时间:78
三元时间:47
结果:
如果-否则= 419813
三元 = 587712
代码:
unsigned long timer1, timer2;
volatile uint32_t x;
timer1 = micros();
for (uint32_t iterator = 0; iterator < 10000000; iterator++)
{
if (iterator & 1)
{
x = 1;
}
else
{
x = 2;
}
}
timer1 = micros() - timer1;
timer2 = micros();
for (uint32_t iterator = 0; iterator < 10000000; iterator++)
{
x = (iterator & 1) ? 1 : 2;
}
timer2 = micros() - timer2;
LOG("if-else = ");
LOGLN(timer1);
LOG("ternary = ");
LOGLN(timer2);