C++ 三元运算符 ?: vs if...else
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3565368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ternary operator ?: vs if...else
提问by Xirdus
In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code?
在 C++ 中, ?: 运算符是否比 if()...else 语句更快?它们在编译后的代码中有什么区别吗?
回答by Kirill V. Lyadvinsky
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
.
你不能对if-else
.
回答by ptomato
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.
取决于您的编译器,但在任何现代编译器上通常没有区别。这是你不应该担心的事情。专注于代码的可维护性。
回答by jalf
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.
我已经看到 GCC 将条件运算符转换为cmov
(条件移动)指令,同时将if
语句转换为分支,这意味着在我们的例子中,使用条件运算符时代码更快。但那是几年前的事了,很可能在今天,两者都会编译为相同的代码。
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.
不能保证它们会编译为相同的代码。如果您需要性能,那么一如既往地测量. 当您测量并发现 1. 您的代码太慢,以及 2. 正是这段特定的代码是罪魁祸首,然后研究编译器生成的汇编代码并检查自己发生了什么。
Don't trust golden rules like "the compiler will always generate more efficient code if I use the conditional operator".
不要相信诸如“如果我使用条件运算符,编译器将始终生成更高效的代码”之类的黄金法则。
回答by James Curran
They are the same, however, the ternary operator can be used in places where it is difficult to use a if/else:
它们是相同的,但是,三元运算符可以用于难以使用 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.
使用 if/else 执行该语句会生成非常不同的编译代码。
Update after 8 years...
8年后更新……
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")
(实际上,我很确定您可以将第一个字符串中的“%d”替换为“one”)
回答by VS3
Just to be a bit left handed...
只是有点左撇子......
x ? y : x = value
will assign valueto yif xis not 0 (false).
将分配值给ÿ如果X不为0(假)。
回答by QuentinUK
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.
它比 if/else 清楚得多,因为您可以立即看到两个分支都导致 x 被分配给。
回答by amdyes
Regardless the compiled code, They are semantically different thing. <cond>?<true expr>:<false expr>
is an expression and if..else..
is a statement.
无论编译的代码如何,它们在语义上都是不同的。<cond>?<true expr>:<false expr>
是一个表达式并且if..else..
是一个语句。
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.
虽然条件表达式的语法看起来很笨拙,但它是一件好事。您被迫提供 a<false expr>
并且对这两个表达式进行类型检查。
The equivalent to if..else..
in expression-based, functional language like Lisp, Haskell is ? :
in C++, instead of if..else..
statement.
相当于if..else..
在基于表达式的函数式语言(如 Lisp)中,Haskell? :
在 C++ 中,而不是在if..else..
语句中。
回答by Eric
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 :
我认为在某些情况下,内联 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;
}
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.
因此,通过内联 if,我们节省了a
在与b
. 虽然在两种情况下条件评估速度很可能相当,但更改范围迫使您考虑内联 if 允许您避免的其他因素。
回答by Proclyon
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.
是的 使代码 100% 伪造看起来很愚蠢。但是这个小技巧帮助我分析了代码的可读性。这是您在此示例中查看的运算符的可读性,而不是内容。
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
根据我的经验,这是有限的,我见过很少有人能够快速引出三元运算符所需的信息,除非 100% 确定它更好,否则避免使用。当它被窃听时修复也是一种痛苦,我认为
回答by supercat
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.
我希望在大多数编译器和目标平台上,会出现“if”更快的情况和 ?: 更快的情况。也会有一种形式比另一种形式或多或少紧凑的情况。哪种情况支持一种形式或另一种形式将因编译器和平台而异。如果您在嵌入式微控制器上编写性能关键代码,请查看编译器在每种情况下生成的内容,看看哪个更好。在“主流”PC 上,由于缓存问题,查看哪个更好的唯一方法是在类似于真实应用程序的东西中对两种形式进行基准测试。