Skip to content

Instantly share code, notes, and snippets.

@hungdoansy
Created April 28, 2021 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hungdoansy/b5d7e0be6533d8fe012eeff3229457cd to your computer and use it in GitHub Desktop.
Save hungdoansy/b5d7e0be6533d8fe012eeff3229457cd to your computer and use it in GitHub Desktop.
Compare Math.floor and ~~
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