Ternary operator ?: vs if...else
In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code?
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.
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
.
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".
链接地址: http://www.djcxy.com/p/31484.html上一篇: 三元运算符(?:)在Bash中