The various methods are:
Which can be used, for example, like so:
var float = 367.9987; ~~float //367 float | 0 //367 float << 0 //367 float >> 0 //367 float >>> 0 //367
I have set up a test on the great JS Perf website to sample which of these methods is fastest in the various browsers, check out the result and run the tests for yourself here:
So far, my result graph looks like so (for an interactive version please visit the link above):
These results are very interesting. As you can see currently Chrome will handle all of these operations at almost the same speed. However, Internet Explorer handles
Math.floor around 76% slower than a bitwise shift/or.
Surprisingly Safari 7 handles all versions in a slow manner, with the triple bitwise shift (
>>>) being the fastest.
Math.floor has actually been optimised to the fastest but the other methods are still very close behind.
Taking all of this into account, I would suggest using a regular bitwise shift
>> as this is fast in all browsers, including Internet Explorer.
However, that being said the syntax for a bitwise not is more intuitive and looks more natural in the flow of code, for example:
var x = 345.768, y = 0; // Confusing y = (5 * x) << 0; // Nicer y = ~~(5 * x); // Least confusing, but slower y = Math.floor( 5 * x );
So ultimately you must make the choice of which operation to use based on your application, the audience you have and the actual routine you are implementing. Meaning, it's best not to confuse the next programmer who comes along so
Math.floor is best in non performance critical code but
(5 * x) << 0; might be a good idea in a performance bottleneck situation such as on an animated
<canvas> which runs code in a loop many times per second.