Search code examples
performancecpupipelineternary

What is the Performance Cost of Ternary Operator


I've heard compilers are very smart and know how to optimize if / else statements.

I've also heard ternaries are high performance because they go through the CPU's instruction pipeline less.

Let me clarify, based on what I've heard:

An if / else must pass its condition through the pipeline and wait for the result before it can perform the calculations for the outcome.

However a ternary can pass both the outcomes' calculations to the cpu without having to wait for the boolean expression to pass through the pipeline.

So, which is faster, ternaries or if / else ?


Solution

  • There will be no performance difference, ternary operator is just a syntactic sugar.

    From ISO/IEC 9899 C Standard (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. (...)