Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the conditional operator lead to less efficient code?

Can ?: lead to less efficient code compared to if/else when returning an object?

Foo if_else()
{
    if (bla)
        return Foo();
    else
        return something_convertible_to_Foo;
}

If bla is false, the returned Foo is directly constructed from something_convertible_to_Foo.

Foo question_mark_colon()
{
    return (bla) ? Foo() : something_convertible_to_Foo;
}

Here, the type of the expression after the return is Foo, so I guess first some temporary Foo is created if bla is false to yield the result of the expression, and then that temporary has to be copy-constructed to return the result of the function. Is that analysis sound?

like image 979
fredoverflow Avatar asked Aug 05 '11 13:08

fredoverflow


People also ask

Is a ternary operator more efficient?

Difference between if-else statement and ternary operator: The ternary operator is a statement in JavaScript, and a statement is faster than Block. The if-else is a programming block. The ternary operator is more efficient and readable.

Is conditional operator faster than if in C?

It is not faster. There is one difference when you can initialize a constant variable depending on some expression: const int x = (a<b) ?

What does the conditional operator do?

Conditional operators are used to evaluate a condition that's applied to one or two boolean expressions. The result of the evaluation is either true or false.

Which is better conditional operator or if-else?

The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.


2 Answers

A temporary Foo has to be constructed either way, and both cases are a clear candidate for RVO, so I don't see any reason to believe the compiler would fail to produce identical output in this case. As always, actually compiling the code and looking at the output is the best course of action.

like image 196
Dennis Zickefoose Avatar answered Oct 29 '22 22:10

Dennis Zickefoose


It most definitely can where rvalue references are enabled. When one of the two branches is an lvalue and the other an rvalue, whichever way you go, you're going to not get the correct function called for at least one of them. When you do the if statement way, then the code will call the correct move or copy constructor for the return.

like image 25
Puppy Avatar answered Oct 29 '22 21:10

Puppy