3 ms·
This is not branchless. It's if-less. But the ternary operator (?:) is a branching instruction.
by maxk42 9y ago
This is not branchless.
It's if-less. But the ternary operator (?:) is a branching instruction.
- colejohnson66 9y agoNot necessarily. A compiler can optimize ?x:0 into a multiply. For example, f(x) ? y : 0 can also be written as (int)(bool)f(x) * y
- Atrix256 9y agoHere's a godbolt to play with as well, showing how it does actually compile down to being branchless in clang (you can switch it to use other compilers too) https://goo.gl/bywp8b https://goo.gl/bywp8b
- pjscott 9y agoIn case anybody was wondering, the x86 assembly is doing the multiply trick. The rather confusing "lea" instruction -- Load Effective Address -- is used as a space-efficient way of saying "take one register, multiply by 1, 2, 4, or 8, add another register, and put it in a third register". The thing in the register that gets multiplied by that constant is either a 1 or a 0. If the constants had been less convenient numbers, like 42, the compiler could have instead used a conditional move instruction -- more general-purpose, but I believe slightly larger and often ever-so-slightly slower.
- Tenobrus 9y agoThis, and using explicit multiplication as an alternative depending on your compiler, is mentioned in the article.
- pandaman 9y agoIt's a conditional instruction but it can be implemented without branching. The difference is that you can execute arbitrary instructions after a branch but the select (operator-?) does not change the instruction flow. SIMD processors can do parallel select but cannot do parallel diverging branches.
- deleted 9y ago[deleted]