Rounding numbers down
JavaScript performance comparison
Info
Note that some of the listed alternatives to Math.floor() use bitwise operators, which convert numbers to a 32-bit sequence.
These alternatives will only work with positive signed 32-bit floats, i.e. numbers from 0 to +2,147,483,647 (2^31-1).
~~2147483647.1; // 2147483647
~~2147483648.1; // -2147483648
Preparation code
<script>
var n = Math.PI,
// 3.141592653589793
floorNew = (function() {
var f = Math.floor,
cap = 2 ^ 31;
return function(n) {
return n >= 0 && n < cap ? ~~n : f(n);
}
})();
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Math.floor |
|
pending… |
parseInt |
|
pending… |
Double bitwise NOT |
|
pending… |
Bitwise OR |
|
pending… |
Bitwise OR with 0 |
|
pending… |
Bitwise AND |
|
pending… |
Bitwise left shift |
|
pending… |
Math.floor + ~~n |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 1: published by Mathias Bynens and last updated
- Revision 2: published
- Revision 3: published and last updated
- Revision 4: published and last updated
- Revision 5: published by Jordan
- Revision 6: published by NilColor
- Revision 11: published
- Revision 12: published by Jack Rugile
- Revision 13: published
- Revision 14: published
- Revision 15: published
- Revision 18: published by Luin
0 comments