Flash Cookbook - Appendix - optimizing flash code Part 3 - calculating distance between two points
Let's declare two points p1 and p2. We want to calculate their distance. What do we do?
First there is the Point class's distance function:
(1) var distance:Number = Point.distance(p1, p2);
Are there other ways to do this? Yes, to use the standard equation in our toolbox:
distance = sqrt( squareof(p2.x-p1.x) + squareof(p2.y-p1.y)).
Even using this formula there are several ways of manifesting this (we show two ways now):
(2) var distance:Number = Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
and
(3) var distance:Number = Math.sqrt((p2.x - p1.x)*(p2.x - p1.x) + (p2.y - p1.y)*(p2.y - p1.y));
The major difference between these last two is that the first one uses the built in math power function.
Let's compare the three methods with our standard test: apply each one of them a million times, measure them nine times and see the statistics. And what the numbers say.
(1) 1639.44 ms, deviation 3.48 ms
(2) 744.33 ms, deviation 1.56 ms
(3) 343 ms, deviation 0.33 ms
(note that the empty loop of measure runs in 8.67 ms with deviation 0.11 ms, as it is)
Yes, the values above are surprising. Consider them when you create your code.
(For curious people: the deviation decreases with the mean.)