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?
Yes! The second is vastly more readable.
We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators. Although it follows the same algorithm as of if-else statement, the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.
The ternary operator is a common tool that you'll see a lot in JavaScript code. It can make your code concise but it can also make your code unreadable if you don't use it properly. Try to keep the ternaries simple and readable.
Here are the main differences between ternary operators and if-else blocks: A ternary operator is a single statement, while an if-else is a block of code. A ternary operator is faster than an if-else block.
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 IT
instruction you mentionned, for if and ternary:
MOVS R1, #2
CMP R0, #0
IT GT
MOVGT R1, #1
MOV.W R2, #3
IT GT
MOVGT R2, #4
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.
No.
There are no winners at code golf.
Readability wins.
So in this case your first example using traditional conditional blocks is about 7099092034902 times easier to read. Anyone even remotely familiar with programming will be able to understand what is going on.
In the latter example... God, what is that!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With