Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference using std::min or ternary operator?

Tags:

c++

c++11

Is there any performance difference in using

a = a <= b ? a : b;

versus

a = std::min(a, b);

In the code where I am working the first form is used but the variable names are quite long which makes it hard to read. I would prefer to use the second but not sure if there is any performance difference.

like image 831
skeept Avatar asked Oct 09 '15 21:10

skeept


People also ask

Is ternary 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) ?

Are ternary operators faster than if?

Yes! The second is vastly more readable.

Are ternary operators faster JS?

There is no difference in speed. Some prefer the if/else for readability. Personally, I use the ternary operator whenever the logic is trivial enough to understand on one line.

Is ternary operator branchless?

This is not branchless. It's if-less. But the ternary operator (?:) is a branching instruction.


1 Answers

I tested it with gcc -O2 and both produced the exact same assembly. There is no difference at all.

like image 172
Baum mit Augen Avatar answered Sep 27 '22 20:09

Baum mit Augen