三元运算符 ?: 与 if...else

发布于 2024-09-15 14:06:39 字数 57 浏览 9 评论 0原文

在 C++ 中,?: 运算符比 if()...else 语句更快吗?它们之间的编译代码有什么区别吗?

In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

土豪我们做朋友吧 2024-09-22 14:06:40

它并不更快。当您可以根据某个表达式初始化常量变量时​​,有一个区别:

const int x = (a<b) ? b : a;

您不能使用 if-else 执行相同的操作。

It is not faster. There is one difference when you can initialize a constant variable depending on some expression:

const int x = (a<b) ? b : a;

You can't do the same with if-else.

锦欢 2024-09-22 14:06:40

取决于您的编译器,但在任何现代编译器上通常没有区别。这是你不应该担心的事情。专注于代码的可维护性。

Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.

半山落雨半山空 2024-09-22 14:06:40

我见过 GCC 将条件运算符转换为 cmov(条件移动)指令,同时将 if 语句转换为分支,这意味着在我们的例子中,使用时代码速度更快条件运算符。但那是几年前的事了,而且很可能在今天,两者都会编译成相同的代码。

不能保证它们会编译成相同的代码。如果您需要性能,那么一如既往地测量。当您测量并发现 1. 您的代码太慢,以及 2. 罪魁祸首是这段特定的代码块时,请研究编译器生成的汇编代码并亲自检查发生了什么。

不要相信“如果我使用条件运算符,编译器总是会生成更有效的代码”之类的黄金法则。

I've seen GCC turn the conditional operator into cmov (conditional move) instructions, while turning if statements into branches, which meant in our case, the code was faster when using the conditional operator. But that was a couple of years ago, and most likely today, both would compile to the same code.

There's no guarantee that they'll compile to the same code. If you need the performance then, as always, measure. And when you've measured and found out that 1. your code is too slow, and 2. it is this particular chunk of code that is the culprit, then study the assembly code generated by the compiler and check for yourself what is happening.

Don't trust golden rules like "the compiler will always generate more efficient code if I use the conditional operator".

救赎№ 2024-09-22 14:06:40

它们是相同的,但是,三元运算符可以用在难以使用 if/else 的地方:

printf("Total: %d item%s", cnt, cnt != 1 ? "s" : "");

使用 if/else 执行该语句将生成非常不同的编译代码。


8年后更新...

实际上,我认为这样会更好:(

printf(cnt == 1 ? "Total: %d item" : "Total: %d items", cnt);

实际上,我很确定你可以将第一个字符串中的“%d”替换为“one”)

They are the same, however, the ternary operator can be used in places where it is difficult to use a if/else:

printf("Total: %d item%s", cnt, cnt != 1 ? "s" : "");

Doing that statement with an if/else, would generate a very different compiled code.


Update after 8 years...

Actually, I think this would be better:

printf(cnt == 1 ? "Total: %d item" : "Total: %d items", cnt);

(actually, I'm pretty sure you can replace the "%d" in the first string with "one")

思念绕指尖 2024-09-22 14:06:40

无论编译后的代码如何,它们在语义上都是不同的。 ?: 是一个表达式,if..else.. 是一个语句。

虽然条件表达式的语法看起来很别扭,但却是一件好事。您必须提供 并且对两个表达式进行类型检查。

相当于 Lisp、Haskell 等基于表达式的函数式语言中的 if..else..? : 在 C++ 中,代替 if..else.. 语句。

Regardless the compiled code, They are semantically different thing. <cond>?<true expr>:<false expr> is an expression and if..else.. is a statement.

Although the syntax of conditional expression seems awkward, it is a good thing. You are forced to provide a <false expr> and the two expressions are type checked.

The equivalent to if..else.. in expression-based, functional language like Lisp, Haskell is ? : in C++, instead of if..else.. statement.

天荒地未老 2024-09-22 14:06:40

只是有点左撇子...

x ? y : x = value

如果x不为0(假),则将分配给y

Just to be a bit left handed...

x ? y : x = value

will assign value to y if x is not 0 (false).

绻影浮沉 2024-09-22 14:06:40

您不必被迫将其全部放在一行上:-

x = y==1 ?
    2
    :// else
    3;

它比 if/else 清楚得多,因为您可以立即看到两个分支都导致 x 被分配。

你也可以声明一个const
例如

int const x = y==1 ?
            2
            :// else
            3;

,const 对编译器很有用,可以使代码更加优化。

You are not forced to put it all on one line:-

x = y==1 ?
    2
    :// else
    3;

It is much clearer than if/else because you can see immediately that both branches lead to x being assigned to.

You can also declare a const
eg

int const x = y==1 ?
            2
            :// else
            3;

And a const can be useful to the compiler to make the code more optimised.

著墨染雨君画夕 2024-09-22 14:06:40

我预计在大多数编译器和目标平台上,都会出现“if”更快的情况和 ?: 更快的情况。还存在一种形式比另一种形式或多或少紧凑的情况。哪种情况有利于一种形式或另一种形式会因编译器和平台的不同而有所不同。如果您在嵌入式微控制器上编写性能关键的代码,请查看编译器在每种情况下生成的内容,看看哪个更好。在“主流”PC 上,由于缓存问题,了解哪个更好的唯一方法是在类似于实际应用程序的情况下对两种形式进行基准测试。

I would expect that on most compilers and target platforms, there will be cases where "if" is faster and cases where ?: is faster. There will also be cases where one form is more or less compact than the other. Which cases favor one form or the other will vary between compilers and platforms. If you're writing performance-critical code on an embedded micro, look at what the compiler is generating in each case and see which is better. On a "mainstream" PC, because of caching issues, the only way to see which is better is to benchmark both forms in something resembling the real application.

内心旳酸楚 2024-09-22 14:06:40

在 CA 三元运算符“?:”可用于构造以下形式的条件表达式

exp1 ? exp2:exp3

,其中 exp1、exp2 和 exp3 是

示例的

        a=20;
        b=25;
        x=(a>b)?a:b;

        in the above example x value will be assigned to b;

表达式这可以使用 if..else 语句编写如下

            if (a>b)
             x=a;
             else
             x=b;

**因此有这两者之间没有区别。这对于程序员来说很容易编写,但对于编译器来说两者是相同的。*

In C A ternary operator " ? : " is available to construct conditional expressions of the form

exp1 ? exp2:exp3

where exp1,exp2 and exp3 are expressions

for Example

        a=20;
        b=25;
        x=(a>b)?a:b;

        in the above example x value will be assigned to b;

This can be written using if..else statement as follows

            if (a>b)
             x=a;
             else
             x=b;

**Hence there is no difference between these two. This for the programmer to write easily, but for compiler both are same.*

素罗衫 2024-09-22 14:06:40

在反转一些代码(几年前我不记得了)时,我看到 :? 的机器代码之间存在单行差异。和 if-else。
不太记得了,但很明显两者的实现是不同的。

但我建议你不要选择其中之一,因为它的效率,根据代码的可读性或你的方便来选择。
快乐编码

During reversing some code (which I don't remember, few years ago) I saw single line difference between the Machine Code of :? and if-else.
Don't remember much but it is clear that implementation of both is different.

But I advise You to not choose one of them b'coz of its efficiency, choose according to readability of code or your convenience.
Happy Coding

浅黛梨妆こ 2024-09-22 14:06:40

三元运算符总是返回一个值。
因此,当您想要从结果中得到一些输出值并且只有 2 个条件时,最好使用三元运算符。
如果上述任何条件不成立,请使用 if-else。

Ternary Operator always returns a value.
So in situation when you want some output value from result and there are only 2 conditions always better to use ternary operator.
Use if-else if any of the above mentioned conditions are not true.

﹏半生如梦愿梦如真 2024-09-22 14:06:40

我认为在某些情况下,内联 if 由于其工作范围而可以产生“更快”的代码。对象创建和销毁的成本可能很高,因此请考虑以下场景:

class A{
    public:
    A() : value(0) {
        cout << "Default ctor" << endl;
    }
    A(int myInt) : value(myInt)
    {
        cout << "Overloaded ctor" << endl;
    }

    A& operator=(const A& other){
        cout << "= operator" << endl;
        value = other.value; 
    }

    ~A(){
        cout << "destroyed" << std::endl;
    }

    int value;

};


int main()
{
   {
       A a;
       if(true){
           a = A(5);
       }else{
           a = A(10);
       }
   }

   cout << "Next test" << endl;
   {
        A b = true? A(5) : A(10);
   }
   return 0;
}

使用此代码,输出将是:

Default ctor                                                                                                                                                                                                                      
Overloaded ctor                                                                                                                                                                                                                   
= operator                                                                                                                                                                                                                        
destroyed                                                                                                                                                                                                                         
destroyed                                                                                                                                                                                                                         
Next test                                                                                                                                                                                                                         
Overloaded ctor                                                                                                                                                                                                                   
destroyed  

因此,通过内联 if,我们节省了在同一范围内保持 a 存活所需的大量操作如b。虽然在两种情况下条件评估速度很可能相当相等,但更改范围会迫使您考虑内联 if 允许您避免的其他因素。

I think that there are situations where the inline if can yield "faster" code because of the scope it works at. Object creation and destruction can be costly so consider the follow scenario :

class A{
    public:
    A() : value(0) {
        cout << "Default ctor" << endl;
    }
    A(int myInt) : value(myInt)
    {
        cout << "Overloaded ctor" << endl;
    }

    A& operator=(const A& other){
        cout << "= operator" << endl;
        value = other.value; 
    }

    ~A(){
        cout << "destroyed" << std::endl;
    }

    int value;

};


int main()
{
   {
       A a;
       if(true){
           a = A(5);
       }else{
           a = A(10);
       }
   }

   cout << "Next test" << endl;
   {
        A b = true? A(5) : A(10);
   }
   return 0;
}

With this code, the output will be :

Default ctor                                                                                                                                                                                                                      
Overloaded ctor                                                                                                                                                                                                                   
= operator                                                                                                                                                                                                                        
destroyed                                                                                                                                                                                                                         
destroyed                                                                                                                                                                                                                         
Next test                                                                                                                                                                                                                         
Overloaded ctor                                                                                                                                                                                                                   
destroyed  

So by inlining the if, we save a bunch of operation needed to keep a alive at the same scope as b. While it is highly probable that the condition evaluation speed is pretty equal in both scenarios, changing scope forces you to take other factors into consideration that the inline if allows you to avoid.

懷念過去 2024-09-22 14:06:40

现在我无法帮助你,我也许可以帮助你解决下面的第二个问题,我想使用它吗?如果你只是想知道速度,请忽略我的评论。

我只能说请非常聪明地了解何时使用三元? : 操作员。对于可读性来说,这既可能是一种祝福,也可能是一种诅咒。

在使用之前问问自己是否觉得它更容易阅读

int x = x == 1 ? x = 1 : x = 1;

if (x == 1)
{
   x = 1
}
else
{
   x = 2
}

if (x == 1)
    x = 1
else
    x = 1

是的,让代码 100% 伪造看起来很愚蠢。但这个小技巧帮助我分析了代码的可读性。您在此示例中查看的是运算符的可读性,而不是内容。

它看起来很干净,但普通的马桶座圈和门把手也很干净。

根据我有限的经验,我看到很少有人实际上能够快速从三元运算符引渡所需的信息,除非 100% 确定它更好,否则请避免。我认为当它被窃听时修复起来也很痛苦

Now I can't help you with that, I may be able to help with a secondary question beneath it, do I want to use it? If you just want to know of the speed, just ignore my comment.

All I can say is please be very smart about when to use the ternary ? : operator. It can be a blessing as much as a curse for readability.

Ask yourself if you find this easier to read before using it

int x = x == 1 ? x = 1 : x = 1;

if (x == 1)
{
   x = 1
}
else
{
   x = 2
}

if (x == 1)
    x = 1
else
    x = 1

Yes It looks stupid to make the code 100% bogus. But that little trick helped me analyse my readability of code. It's the readability of the operator you look at in this sample, and not the content.

It LOOKS clean, but so does the average toilet seat and doorknob

In my experience, which is limited, I have seen very little people actually being able to quickly extradite information required from a ternary operator, avoid unless 100% sure it's better. It's a pain to fix when it's bugged aswell I think

甜心小果奶 2024-09-22 14:06:40

不,它们被转换为完全相同的可执行代码。

No, they are converted to exactly the same executable code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文