Shader optimization: Is a ternary operator equivalent to branching?

Actually this depends on the shader language one uses.

  • In HLSL and Cg a ternary operator will never lead to branching. Instead both possible results are always evaluated and the not used one is being
    discarded. To quote the HLSL documentation:

    Unlike short-circuit evaluation of &&, ||, and ?: in C, HLSL expressions never short-circuit an evaluation because they are vector operations. All sides of the expression are always evaluated.

    For Cg the situation is similar, also here the ternary conditional operator is a vector operator. (documentation):

    Unlike C, side effects in the expressions in the second and third operands are always executed, regardless of the condition.

  • In ESSL and GLSL the ternary operator will always lead to branching. It is not a vector operator, so the condition has to evaluate to a boolean. See the GLSL specification:

    It operates on three expressions (exp1 ? exp2 : exp3). This
    operator evaluates the first expression, which must result in a scalar Boolean. If the result is true, it
    selects to evaluate the second expression, otherwise it selects to evaluate the third expression. Only
    one of the second and third expressions is evaluated.

    (Source for ESSL)

An illustration of the difference is for instance available on the Khronos WebGL test site for ternary operators.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)