Created
April 28, 2021 07:04
-
-
Save hungdoansy/b5d7e0be6533d8fe012eeff3229457cd to your computer and use it in GitHub Desktop.
Compare Math.floor and ~~
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
const getNumbers = () => { | |
const numbers = []; | |
for(let i = 0; i < 50000; i++) { | |
const n = +(Math.random() * 10000).toFixed(5); | |
numbers.push(n); | |
} | |
return numbers; | |
} | |
const numbers = getNumbers(); | |
const test1 = () => { | |
let x = 0; | |
for(let i = 0; i < 1000; i++) { | |
numbers.forEach(n => { | |
x = Math.floor(n); | |
}); | |
} | |
}; | |
const test2 = () => { | |
let x = 0; | |
for(let i = 0; i < 1000; i++) { | |
numbers.forEach(n => { | |
x = ~~n; | |
}); | |
} | |
}; | |
let start, end; | |
start = Date.now(); | |
test2(); | |
end = Date.now(); | |
console.log((end-start) / 1000); | |
start = Date.now(); | |
test1(); | |
end = Date.now(); | |
console.log((end-start) / 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment