[Home]WritingFastCode/Distance

Robo Home | WritingFastCode | Changes | Preferences | AllPages

Calculating the distance between two points is a slow operation due to the call to Math.sqrt(). However you can often use the square of the distance.

For example, if you're finding which of two enemies is closer:


Point2D enemyOne;
Point2D enemyTwo;
Point2D me;

//Slow
if(me.distance(enemyOne) < me.distance(enemyTwo)){
   ...
}

//Fast
if(me.distanceSq(enemyOne) < me.distanceSq(enemyTwo)){
   ...
}

The two pieces of code work exactly the same. You can also use this trick for comparing to a constant, like so:


Point2D enemyOne;
Point2D me;

//Slow
if(me.distance(enemyOne) < 100){
   ...
}

//Fast
if(me.distanceSq(enemyOne) < 10000){ // distance is less than 100
   ... 
}

This optimization is only worth doing inside loops that get called a lot, Math.sqrt() a few times is fine but once you start doing thousands of calls it can really slow your bot down.

--David Alves


Discussion

Robo Home | WritingFastCode | Changes | Preferences | AllPages
Edit text of this page | View other revisions
Last edited November 1, 2004 3:35 EST by David Alves (diff)
Search: