function testHypot() {
for (let i=0; i < 1000; i++){
for (let j=0; j < 1000; j++) {
Math.hypot(i, j)
}
}
}
function testSqrt() {
for (let i=0; i < 1000; i++){
for (let j=0; j < 1000; j++) {
Math.sqrt(i*i+j*j)
}
}
}
function testSqrtAndPow() {
for (let i=0; i < 1000; i++){
for (let j=0; j < 1000; j++) {
Math.sqrt(Math.pow(i,2)+Math.pow(j,2))
}
}
}
function testNoSqrt() {
for (let i=0; i < 1000; i++){
for (let j=0; j < 1000; j++) {
i*i+j*j
}
}
}
function testNoSqrtAndPow() {
for (let i=0; i < 1000; i++){
for (let j=0; j < 1000; j++) {
Math.pow(i,2)+Math.pow(j,2)
}
}
}
testHypot()
testSqrt()
testSqrtAndPow()
testNoSqrt()
testNoSqrtAndPow()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
hypot | |
sqrt | |
sqrt + pow | |
i*i | |
pow |
Test name | Executions per second |
---|---|
hypot | 58.5 Ops/sec |
sqrt | 157.9 Ops/sec |
sqrt + pow | 83.7 Ops/sec |
i*i | 781.8 Ops/sec |
pow | 95.9 Ops/sec |
The benchmark created on MeasureThat.net evaluates various approaches for calculating the Euclidean distance between points in a 2D space using JavaScript. This is done by comparing performance across different methods for computing distance, which fundamentally involves operations such as squaring, taking square roots, and using specific mathematical functions.
Math.hypot(i, j):
Math.sqrt(i * i + j * j):
Math.sqrt
function to obtain the distance.Math.hypot
, but it involves manual squaring of the variables which can impact performance slightly as well.Math.sqrt(Math.pow(i, 2) + Math.pow(j, 2)):
Math.pow
function to square the two values. While semantically clear, it can lead to unnecessary performance overhead.Math.pow
.i * i + j * j:
Math.pow(i, 2) + Math.pow(j, 2):
Math.pow
function to square the points, similar to the previous methods but includes function calls which add overhead.Math.pow
.In the latest benchmark results:
i*i
, achieving approximately 781.83 executions per second.Math.sqrt(i*i + j*j)
method follows next but is significantly slower at around 157.89 executions per second.Math.pow
approach is also quite slow when compared to direct arithmetic.Math.hypot:
Math.sqrt with direct multiplications:
Math.hypot
, also provides a straightforward formula.Math.sqrt with Math.pow:
Direct arithmetic (i*i):
Math.pow:
While the benchmark primarily tests methods intended for straightforward distance calculations, other alternatives could involve more advanced libraries or techniques:
This benchmark provides valuable insights for software engineers, helping them choose the most suitable method for distance calculations based on their specific needs for performance and complexity.