Get the full commented source code of

HTML5 Suika Watermelon Game

Talking about Php and PROgramming.

While I was reading Claytus Hood Tower Defense case study I was impressed by this:

To estimate the distances and so check the range, I use Manhattan distance formula, less accurate but faster than Euclidian distance

Named after the grid layout of most Manhattan streets, it’s a form of geometry in which the usual metric of Euclidean geometry is replaced by a new metric in which the distance between two points is the sum of the absolute differences of their coordinates (for more information refer to Wikipedia’s Taxicab geometry page).

Now the question is: is Manhattan distance really faster than Euclidian distance?

For the following test I used PHP, but feel free to make it in any other language and I’ll be glad to publish your results.

First, I set two variables, named $x_dist and $y_dist, to 10 and 20 respectively, then to -10 and -20

These variables should represent the x and y distance between two points.

I generated a script to calculate a million times the distance with Euclidean geometry this way:

$distance = sqrt($x_dist*$x_dist+$y_dist*$y_dist);

The server took an average 566.56 milliseconds to give me the response.

I thought most of the time is spent to calculate the square root, so a smart programmer could remove the square root and eventually compare the result with a given number multiplied by itself… so if the distance has to b less than 30, I will check if it’s less than 30*30=900.

This way to determine the distance:

$distance = $x_dist*$x_dist+$y_dist*$y_dist;

took an average time of 204.43 milliseconds to generate a million results.

Then it’s time to use Manhattan distance:

$distance = abs($x_dist)+abs($y_dist);

This method took 694.83 milliseconds… the slowest so far… so I tried to avoid using abs this way:

if($x_dist<0){
	$x_dist *=-1;
}
if($y_dist<0){
	$y_dist *=-1;
}
$distance = $x_dist+$y_dist;

and I got 243.11 milliseconds. Trying with positive or negative starting distance values did not change response times in a valuable manner.

So I would say: "Myth Busted".

Do you agree?

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.