Comparing Math.floor(), parseInt and a (bitwise) shift in Javascript
arnorhs.com
arnorhs.com
1. it will always behave correctly (barring implementation bugs)
2. readable/mantainable code comes first
3. leave tricks to the interpreter
4. you're not gonna do 60 million flooring ops/s
5. -1.1 is really -2+.9
The author missed the ~~1.1 trick (essentially the same as << 0).But for practical reasons I'll stick with Math.floor. It makes my code more readable. Plus, Chrome is already faster using Math.floor. I'm sure the other browsers will catch up, or I at least hope they will.
Actually, that's a bit of a lie: when I wrote SHA3 candidates in JS, they were bitwise-operation-heavy and they probably did have slow [ToInt32] calls in the middle of performance-critical loops. But you see my point: I've never seen or written code whose performance would be significantly impacted by writing x | 0 in place of Math.floor(x). Maybe the number of keystrokes is saved, that might be a good argument, but the performance?
[
1 << 30 === Math.pow(2, 30),
1 << 31 === -Math.pow(2, 31),
0xf0000000 >>> 1 === 0x78000000,
0xf0000000 >> 1 === 0x78000000 - Math.pow(2, 31)
];
// ==> [true, true, true, true]
As pointed out elsewhere in this thread there is one exception to this rule: 0xf0000000 >>> 0 === 0xf0000000;
// ==> true
In other words, right shifting is always unsigned.