2

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?

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • 1
    Well, `Math.hypot` does [do](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot#description) [more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot#polyfill) than just `Math.sqrt`, but performance also seems to be browser dependent; that benchmark link under Firefox is almost a wash (`4606` vs `4493`) whereas in Chrome and Safari it's a complete rout (`4519` vs `164` and `9276` vs `294` respectively). – msbit Apr 17 '22 at 00:16
  • Do any of those implementations do anything special that would take more work, like not underflowing or overflowing `x*x` with x = `DBL_MIN` or `DBL_MAX`? If you just get `0` or `+Inf` from `hypot(DBL_MIN or MAX, 0)`, then it's probably just doing the same thing as `sqrt(x*x + y*y)`. But if you get the original number back even in that case where the temporary would overflow, it must be doing something more than the straightforward "naive" implementation. – Peter Cordes Apr 17 '22 at 00:23
  • @msbit Gotcha, feel free to add that as an answer if you want. That makes sense. I didn't know `hypot` had all that extra functionality. – Ryan Peschel Apr 17 '22 at 00:57
  • @RyanPeschel I'm happy to leave it at a comment ✌️ – msbit Apr 17 '22 at 09:16
  • Closely [related question](https://stackoverflow.com/questions/3764978/why-hypot-function-is-so-slow) – njuffa Apr 21 '22 at 08:04

0 Answers0