Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator vs if statement: compiler optimization

Is this:

int val;  
// ...
val = (val != 0) ? otherVal : 0;

less efficient than this:

int val;
//...
if (val != 0)
    val = otherVal;

?

Are compiler able to optimize the ternary operator? The intent is clear, is there any way it could be wanted to actually write 0 to memory? Maybe when memory is mapped to a file?

Can we assume it doesn't matter?

EDIT: The point is to set a variable to some value if one condition is met. There is no wanted else branching. which is why I ask if a ternary (with obligatory else branch that is supposed to make a copy) will be less efficient or optimized.

like image 555
Aki Avatar asked May 22 '13 16:05

Aki


2 Answers

Mats Petersson suggestion is generally the best "Write the most readable variant". However, if you are trying to write optimal speed performance code, you need to know more info about your computer and processor. With some machines, the first will run faster (highly pipelined processors: no branching, optimized ternary operator). Other machines will run quicker with the second form (simpler).

like image 159
chux - Reinstate Monica Avatar answered Sep 19 '22 04:09

chux - Reinstate Monica


You could use a branchless ternary operator, sometimes called bitselect ( condition ? true : false).

Don't worry about the extra operations, they are nothing compared to the if statement branching.

bitselect implementation:

inline static int bitselect(int condition, int truereturnvalue, int falsereturnvalue)
{
    return (truereturnvalue & -condition) | (falsereturnvalue & ~(-condition)); //a when TRUE and b when FALSE
}

inline static float bitselect(int condition, float truereturnvalue, float falsereturnvalue)
{
    //Reinterpret floats. Would work because it's just a bit select, no matter the actual value
    int& at = reinterpret_cast<int&>(truereturnvalue);
    int& af = reinterpret_cast<int&>(falsereturnvalue);
    int res = (at & -condition) | (af & ~(-condition)); //a when TRUE and b when FALSE
    return  reinterpret_cast<float&>(res);
}
like image 34
Yochai Timmer Avatar answered Sep 18 '22 04:09

Yochai Timmer