0

I have seen two types of if/else, which one is faster?

if(a==b) cout<<"a";
else cout<<"b";

OR

a==b ? cout<<"a" : cout<<"b";
  • 3
    If you care you have to measure. – Richard Critten Jan 31 '18 at 17:19
  • 1
    Why should one be faster then the other? –  Jan 31 '18 at 17:20
  • 2
    Don't worry about this at all. You will have to worry about a lot of other things when writing an application that solves some real world problems. – R Sahu Jan 31 '18 at 17:21
  • Premature optimisation is the root of all evil.... don't do it. – UKMonkey Jan 31 '18 at 17:27
  • 1
    I say if it takes 1 billionth of a second or even 20 billionths of a second more how would you even know? The `cout` is going to take much longer. – drescherjm Jan 31 '18 at 17:29
  • How about `std::cout << (a == b)["ba"];` ? :-) – Jarod42 Jan 31 '18 at 17:34
  • 2
    Speed up your algorithms, use efficient data structures, and not concern yourself with rinky-dink `if` statements. – PaulMcKenzie Jan 31 '18 at 17:35
  • 1
    The truth is in the assembly language output. Most processors require at least 2 instructions for a conditional expression: compare and branch. Most processors don't like branch instructions because they may cause a reload of the instruction cache. Regardless, generate the assembly language for each example and compare them. Reduce branching if possible. – Thomas Matthews Jan 31 '18 at 18:04

2 Answers2

4

The ternary conditional is an abuse since it's a mere coincidence that decltype(cout<<"a") is a type that can be used in a ternary conditional:

cout << (a == b ? "a" : "b");

would be more palatable, and possibly more tractable than the if, else, which you should otherwise prefer for its clarity.

And trust your compiler to make the optimisations. checking the output assembly if you have any suspicions.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

The performance of either would never be catastrophic for your program.

It all comes down to Code readability.

The tertiary operator has its limitation of only one statement either true or false.

theboringdeveloper
  • 1,429
  • 13
  • 17