0

I was doing a programming task in JavaScript when I found out that a formula that involves an absolute value between substractions and a sum (Manhattan distance) is less efficient in execution time than a formula that involves the square root of the sums of two powered expressions (Euclidian distance). Am I doing something wrong here or is it normal? I thought the absolute value would not be very difficult to execute.

function Man_dist(x0, y0, x1, y1) {
  return Math.abs(x1 - x0) + Math.abs(y1 - y0);
}

function Eucl_dist(x0, y0, x1, y1) {
  return Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2));
}

I am using console.time("Execution time") to test the performance, and I see that Eucl_dist is usually few microseconds lower than Man_dist:

  console.time("Man Execution time");
  Man_dist(5, 3, 24, 23);
  console.timeEnd("Man Execution time");
  
  console.time("Eucl Execution time");
  Eucl_dist(5, 3, 24, 23);
  console.timeEnd("Eucl Execution time");

I posted the code I am using for benchmarking as per @Bergi suggestion

  • 2
    Why are you using `Number()` in one of these and not the other? Are you sure that that's not the cause of the difference in performance? – JLRishe Nov 15 '20 at 16:26
  • I just noticed this difference, but it is still giving similar results, even though after removing the Number() conversion it is giving better results. I still get better performance with Eucl_dist which I do not understand – VIREN SAJJU DHANWANI DHANWANI Nov 15 '20 at 16:55
  • Thanks. I really doubt that `console.time` is accurate enough to measure the difference in performance between those two. – Bergi Nov 15 '20 at 17:19
  • @JLRishe seems right. After removing the `Number` calls, the `Man_distance` is a tiny bit faster than the `Eucl_distance`. – Bergi Nov 15 '20 at 17:23
  • Is there a more accurate way to measure difference in performance @Bergi? – VIREN SAJJU DHANWANI DHANWANI Nov 15 '20 at 17:32
  • Measure the actual code that involves running these functions multiple times with different numbers, [not artificial examples](https://mrale.ph/blog/2012/12/15/microbenchmarks-fairy-tale.html). In your example, I'd guess the `console.time` calls have a larger overhead than the actual distance calculations. – Bergi Nov 15 '20 at 18:36

0 Answers0