I have this block in my program:
if (x > 0) {
a = 1;
b = 4;
} else {
a = 2;
b = 3;
}
This can be written with ternary operation like this:
a = (x > 0) ? 1 : 2;
b = (x > 0) ? 4 : 3;
The results are equivalents, but it’s part of a really critical part of my application, running thousands of times per second. I want to squeeze some microseconds, because this method will grow a little.
My question: in ARM level, which one is faster? I believe the first one creates a branch instruction. But what about the ternary operation? Does it become a branch on iPhone, too? Or iPhone’s ARM has a evil opcode to do the job?
BTW, I also saw an evil technique like this:
a = (x > 0) * 1 + (x <= 0) * 2;
Is this really faster?
EDIT:
Just compiled your example, using GCC/LLVM, different optimizations, and looking at ARM6 and ARM7 assembly, here are my conclusions:
Here is the most concise result with LLVM / ARM7, using the
ITinstruction you mentionned, for if and ternary:ENDOFEDIT
Just searched a bit on the topic and even if some people thinks ternary is less optimized the most results and more relevant says that it produce the same assembly code.
Take care that it might change with :
I’m a bit lazy right now to disassemble code, but maybe I’ll edit that answer later.
So I would think that djna is right, appart the the 2*
(x>0), which would be really surprising if not optimized, this is the same.After that, ternary or not, it is a matter of taste.
I prefer ternary when it makes sense in code and is readable.
About second example it is a trick that use the fact that true == 1 / false == 0…
Funny, but I wouldn’t like to maintain that code.