--David Alves Discussion |
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.