4 ms·
Branching is the expensive part, not comparisons.
by jacobolus 6y ago
Branching is the expensive part, not comparisons.
- cogman10 6y agoThis is 3 branches. The Math method ends up with 4. This is one of those cases where I think it is much more readable to just write the code than to puzzle over what Math.min(Math.max(min, num), max); might be doing. if (num < min) return min; if (num > max) return max; return num; That's how I'd write it. May not be super terse, but anyone that stumbles on this will know precisely what's happening without needing to take a few seconds to puzzle things out.
- jacobolus 6y agoWhat you want is something that compiles to conditional moves. A good compiler should compile your proposed version to the same machine code as the max & min method. If for one reason or another it compiles to branches, it’ll end up being slower. In Javascript in my browser (Safari) when these methods get called enough to get compiled using the most aggressive stage of the JIT, they end up essentially the same speed. On my laptop either one runs about 145 million times per second on one CPU core. I wouldn’t be surprised if a C compiler ended up making this function significantly faster, but I haven’t tested it.