If you happened to be in the middle of watching The Hobbit: The Desolation of Smaug and were suddenly shaken by the unmistakable urge to figure out if Math.pow()
is faster than just multiplying the values together, here are the results:
The code I used for this very unofficial benchmark is:
// Let's run a benchmark comparing Math.pow vs multiplication
const iterations = 10000000;
const x = 2;
console.log("Running performance test...");
// Test Math.pow
const startPow = performance.now();
for (let i = 0; i < iterations; i++) {
Math.pow(x, 4);
}
const endPow = performance.now();
const powTime = endPow - startPow;
// Test multiplication
const startMult = performance.now();
for (let i = 0; i < iterations; i++) {
x * x * x * x;
}
const endMult = performance.now();
const multTime = endMult - startMult;
console.log(`Math.pow time: ${powTime.toFixed(2)}ms`);
console.log(`Multiplication time: ${multTime.toFixed(2)}ms`);
console.log(`Math.pow is ${(powTime / multTime).toFixed(2)}x slower than multiplication`);
I am multiplying a number to the 4th power, but the results were similar even when I was squaring or cubing the values.
The net result of this is: If your app’s biggest performance problem is in your use of Math.pow()
, then do update your code to remove them. For 99.999% of the rest of us, consider this fun trivial knowledge with no actionable real work.
Cheers,
Kirupa