Optimization tip: don’t use sqrt when comparing distances

7 Jul

When comparing distances, whether it be for collision detection in games or drawing circles or discs (like in this recent Geeks3D post) I often see people using sqrt when they are comparing distances. This sqrt is not needed and only wastes CPU or GPU time.

The distance between two points is calculated by taking the length of the vector between the two points, in other words by taking the square root of the dot product of the difference between the two points.

\sqrt{\left(p_{1}-p_{0}\right)\cdot\left(p_{1}-p_{0}\right)}

If we do circle or sphere collision detection, we need to compare the sum of the radii with the distance between the centers:

r_{1}+r_{0}>\sqrt{\left(p_{1}-p_{0}\right)\cdot\left(p_{1}-p_{0}\right)}

If this equation evaluates to true, the circles or spheres collide. Though as you can see, we can get rid of the sqrt by squaring both sides:

\left(r_{1}+r_{0}\right)^{2}>\left(p_{1}-p_{0}\right)\cdot\left(p_{1}-p_{0}\right)

In case of the circle drawing in the GLSL shader we only have to calculate this squared radius once and pass it as a uniform. But even if we would have to do it each frame like in the case of collision detection, a multiplication is a lot faster than a square root.

Don’t use pow to square btw, use a simple multiplication. The pow method should only be used when the power to be used is unknown at compile time.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: