三元运算符vs if语句:编译器优化

Aki*_*Aki 6 c c++ optimization ternary-operator

这是:

int val;  
// ...
val = (val != 0) ? otherVal : 0;
Run Code Online (Sandbox Code Playgroud)

效率低于此:

int val;
//...
if (val != 0)
    val = otherVal;
Run Code Online (Sandbox Code Playgroud)

编译器是否能够优化三元运算符?意图很明确,有没有什么方法可以实际写0到内存?也许当内存映射到文件?

我们可以假设没关系吗?

编辑:关键是如果满足一个条件,将变量设置为某个值.没有其他想要的分支.这就是为什么我问三元(具有强制性的其他分支应该制作副本)是否会降低效率或优化.

Yoc*_*mer 6

您可以使用无分支三元运算符,有时称为位选择(条件?真:假)。

不用担心额外的操作,它们与 if 语句分支相比根本不算什么。

位选择实现:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 三元运算符不是无分支的。有像 bitselect 这样的实现,以无分支的方式实现整数的三元运算(就像我在这里展示的那样)。正如您所看到的,代码中没有实际的三元运算符。 (2认同)

chu*_*ica 5

Mats Petersson 的建议通常是最好的“编写最易读的变体”。但是,如果您正在尝试编写最佳速度性能代码,则需要了解有关您的计算机和处理器的更多信息。对于某些机器,第一个将运行得更快(高度流水线化的处理器:无分支、优化的三元运算符)。使用第二种形式(更简单),其他机器会运行得更快。