4 ms·
Here'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) htt
by Atrix256 9y ago
Here'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.