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