I am performing a ton of distance calculations in my code, to the point where Math.sqrt(a*a + b*b)
is run hundreds of thousands of times.
I then recalled how there is a Math.hypot
function that does exactly this. However, in all the testing I've done, it seems significantly slower than doing Math.sqrt
. For example, if you run the following code:
var i, tmp, x = 55, y = 66, end, ini = performance.now();
// Math.sqrt operation
i = 0;
ini = performance.now();
tmp = 0;
while(i++ < 2000000){
tmp += Math.sqrt(x*x + y*y)
}
end = performance.now();
console.log(tmp, "Math.sqrt operation: " + (end - ini) + " ms");
// Math.hypot
i = 0;
ini = performance.now();
tmp = 0;
while(i++ < 2000000){
tmp += Math.hypot(x, y)
}
end = performance.now();
console.log(tmp, "Math.hypot: " + (end - ini) + " ms");
On my computer the hypot
function is 5x slower. And I tried a benchmarking site as well and there it was 25x slower.
What is causing the hypot
function to be so slow? Should it not be used at all for performance critical distance calculations, or am I doing something wrong?