If you want to compare the performance of multiple functions in JS, console.time()
is your help.
Here is an example with Math.round()
and Number.prototype.toFix()
.
You can see Math.round()
is the winner.
Code
function one(number) {
return Math.round(number * 100) / 100;
}
function two(number) {
return number.toFixed(2);
}
let NUM_TRIALS = 1000000;
[one, two].forEach((func) => {
console.time(func.name);
for (let i = 0; i < NUM_TRIALS; ++i) {
func(Math.random())
}
console.timeEnd(func.name);
});
Result
one: 23.06201171875 ms
two: 301.661865234375 ms