The main reason why Math.floor
may be slower (although in some tests it has been shown to be faster) is due to the function call involved. In older JavaScript implementations, function calls could not be inlined. Newer engines can inline the call or speed up the property lookup, but a guard condition is still needed in case the Math.floor
function was overwritten. The overhead is minimal, so there isn't much difference in speed.
Moreover, as pointed out in various comments, the alternative methods are not identical. They rely on bitwise operations, which automatically convert operands to 32-bit integers by truncating the number. This works well for numbers within 32 bits, but JavaScript numbers are 64-bit floats, which can exceed 2147483647.
Furthermore, negative numbers produce different results since converting them to integers truncates, while Math.floor
always rounds down. For instance, Math.floor(-2.1) === -3
, whereas (-2.1) | (-2.1) === -2
.
If you are absolutely certain that you only have positive numbers below 2147483648 and want optimal performance in older browsers (after verifying that it is actually the bottleneck), consider using an even simpler method: x|0
. This avoids evaluating the variable twice and functions correctly even if x
is an expression (just remember to use parentheses to avoid precedence issues).