三元运算符是否比为变量设置不同值的 if 语句效率低

Is ternary operator less efficient than an if statement that sets a different value to a variable

示例 1:

a = a > b ? b : a

示例 2:

if (a > b)
    a = b

虽然差异可能不大,但我认为示例 2 在计算上更有效,如示例 1 所示,如果 a < b,则 a 的相同值仍然放在变量 a 中,这是不必要的操作,在 if 语句中避免的操作。

另一方面,我在想也许编译器理解这一点并且两个语句以相同的效率工作post编译因为它们对应于相同的指令?

在你的例子中,你的 ternary 操作和你的 if 语句不一样,因为你没有 else语句在if之后,所以它只检查是否a>b.

如果你对语义相等三元运算if-else块的性能差异问题感兴趣,那么答案是No,没有太大区别。三元运算符只是写if-else.

的语法糖

这是最简单的Java程序中的字节码比较,只有一个(entry-point)主要方法,第一种情况我实现三元运算符,在第二个 - if-else 语句中。

 //First example, having Ternary Operator
  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_1
       3: istore_2
       4: iload_1
       5: iload_2
       6: if_icmple     13
       9: iload_2
      10: goto          14
      13: iload_1
      14: istore_1
      15: return
}

//Second Example, having if-else alternative
  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_1
       3: istore_2
       4: iload_1
       5: iload_2
       6: if_icmple     14
       9: iload_2
      10: istore_1
      11: goto          16
      14: iload_1
      15: istore_1
      16: return
}