3 ms·
If implementation of ~~ is supposedly faster than Math.floor() for positives, shouldn't the JIT pick up on this with a guard/deopt block?
by krackers 3y ago
If implementation of ~~ is supposedly faster than Math.floor() for positives, shouldn't the JIT pick up on this with a guard/deopt block?
- lifthrasiir 3y agoBecause `Math.floor` is correct for all numbers but `~~` will be incorrect outside of int32 ranges and non-numbers (`Math.floor("asdf")` is NaN but `~~"asdf"` is 0). Basically it is a shorthand for limited cases, but it is so convenient for those cases that I think it is a worthy trick to know with caveats. ADDED: As per performance, there is a difference, but it is hard to quantify exactly. `Math.floor` with large enough argument won't fit in any integer type, so JIT can't assume that. But it is mostly the case that floating point arithmetics are as fast as integer arithmetics in modern architectures, so unless we completely know how floor outputs are to be used, that argument can't be used to prefer either `Math.floor` or `~~`.
- mpixel 3y agoBitwise operators only work on the first 32-bits, so it isn't as easy as `instead of doing the Math.floor operations, check for edge cases and just the same operation as ~~`