三元操作符? : vs if... else

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

122330 次浏览

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.

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

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.

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")

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".

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

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.

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.*

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

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.

Just to be a bit left handed...

x ? y : x = value

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

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.

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.

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.