Created
August 22, 2011 14:05
-
-
Save Olical/1162452 to your computer and use it in GitHub Desktop.
Very fast rounding in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Number.round = function() { | |
return (this + 0.5) << 0; | |
}; |
Thanks for the trick!
You know what surprised me? That when you put the bitshifting stuff in a function, it is faster than applying it every time on the number literally. Have a look:
(() =>{
const time = f => {
let start = Date.now()
f()
console.log('Needed ', Date.now() - start, ' ms')
}
const round = x => x + 0.5 << 0
const N = 10000000
console.log("Testing O(n) for rounding with n =",N)
console.log("Math.round\n")
time(() => {
for (let i = 1; i <= N; i++)
Math.round(50/i)
})
console.log("bit shift\n")
time(() => {
for (let i = 1; i <= N; i++)
(50/i) + 0.5 << 0
})
console.log("bit shift in own function\n")
time(() => {
for (let i = 1; i <= N; i++)
round(50/i)
})
})()
gave me this in newest Firefox:
Testing O(n) for rounding with n = 10000000
Math.round
Needed 690 ms
bit shift
Needed 10
bit shift in own function
Needed 8 ms
In node.js however it is nearly identical speed for all of them:
Testing O(n) for rounding with n = 1000000
Math.round
Needed 3 ms
bit shift
Needed 1 ms
bit shift in own function
Needed 1 ms
Testing O(n) for rounding with n = 10000000
Math.round
Needed 8 ms
bit shift
Needed 6 ms
bit shift in own function
Needed 6 ms
Testing O(n) for rounding with n = 100000000
Math.round
Needed 52 ms
bit shift
Needed 50 ms
bit shift in own function
Needed 52 ms
Testing O(n) for rounding with n = 1000000000
Math.round
Needed 500 ms
bit shift
Needed 501 ms
bit shift in own function
Needed 495 ms
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works fine with negative numbers.