The best option noted by @ Hosch250 is the triple operator. Take a look at the assembler generated by the JIT compiler for this method:
public static int ternary(int x) { return x == 7 ? 1 : 0; }
Actually, it depends on branch profiling. When your x has a value of 7 quite often, it is compiled as follows:
xor %r11d,%r11d mov $0x1,%eax cmp $0x7,%edx cmovne %r11d,%eax ;*ireturn ; - Test:: ternary@11 (line 12)
See that the triple has been replaced by cmovne , which is not a branch statement.
On the other hand, if you transfer 7 in very rare cases (for example, once every 5000 calls), then the branch is here:
cmp $0x7,%edx je <slowpath> ;*if_icmpne ; - Test:: ternary@3 (line 12) xor %eax,%eax
Now the branch is almost never taken, therefore it is faster to save the state, since the processor branch predictor will almost always be correct. Note that <slowpath> not just return 1; , but also updates the profile of the branch, so if the template changes during program execution ( 7 becomes more common), then the method will be recompiled into the first version.
In general, do not try to be smarter than the JIT compiler in such simple cases.
Tagir valeev
source share