The main reason Math.floor slower (where it actually is in some tests that I did it faster) is that it includes a function call. Older JavaScript implementations could not inline function calls. New engines can build in a call, or at least speed up the search for properties, but they still need a protective condition if you (or some other script) overwrote the Math.floor function. The overhead is minimal, so there is not much difference in speed.
More importantly, though, as mentioned in a few comments, the other methods are not equivalent . All of them work, performing bitwise operations. Bitwise operators automatically convert their operands to 32-bit integers, truncating the number. This is great if the number matches 32 bits, but JavaScript numbers are 64-bit floats, which can be much larger than 2147483647.
They also give a different result for negative numbers, since conversion to integers truncates and Math.floor always rounded. For example, Math.floor(-2.1) === -3 , but (-2.1) | (-2.1) === -2 (-2.1) | (-2.1) === -2 .
If you know you only deal with positive numbers less than 2147483648, and you need to squeeze every bit of performance out of your code in older browsers (first make sure this is a bottleneck. Probably not.), I would use an even simpler method: x|0 . It does not evaluate the variable twice and works even if x is an expression (just remember to put it in parentheses so that you don't run into priority issues).
Matthew Crumley Mar 26 '10 at 23:34 2010-03-26 23:34
source share