三元运算符的性能成本是多少
What is the Performance Cost of Ternary Operator
我听说编译器很聪明,知道如何优化 if / else 语句。
我还听说三元数是高性能的,因为它们较少经过 CPU 的指令流水线。
根据我所听到的,让我澄清一下:
if / else 必须通过管道传递其条件并等待结果,然后才能对结果执行计算。
然而,三元可以将两个结果的计算传递给 cpu,而无需等待布尔表达式通过管道。
那么,三元组还是 if / else 哪个更快?
不会有性能差异,三元运算符只是一个语法糖。
来自 ISO/IEC 9899 C 标准 (draft, page 90):
6.5.15 Conditional operator
(...)
Semantics
The first operand is evaluated; there is a sequence point after its
evaluation. The second operand is evaluated only if the first compares
unequal to 0; the third operand is evaluated only if the first
compares equal to 0; the result is the value of the second or third
operand (whichever is evaluated), converted to the type described
below. (...)
我听说编译器很聪明,知道如何优化 if / else 语句。
我还听说三元数是高性能的,因为它们较少经过 CPU 的指令流水线。
根据我所听到的,让我澄清一下:
if / else 必须通过管道传递其条件并等待结果,然后才能对结果执行计算。
然而,三元可以将两个结果的计算传递给 cpu,而无需等待布尔表达式通过管道。
那么,三元组还是 if / else 哪个更快?
不会有性能差异,三元运算符只是一个语法糖。
来自 ISO/IEC 9899 C 标准 (draft, page 90):
6.5.15 Conditional operator
(...)
Semantics
The first operand is evaluated; there is a sequence point after its evaluation. The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), converted to the type described below. (...)