# Efficient Distance Calculation?

This topic is 4979 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm currently using:
public static double GetDistance( ref float x1, ref float x2, ref float y1, ref float y2 )
{
return Math.Sqrt( ( x1 - x2 )*( x1 - x2 ) + ( y1 - y2 )*( y1 - y2 ) );
}


I call this function many, many, many times per second server-side on my 2D space sim. The number of calls grows exponentially for each player that joins the server, so my question is, am I doing this the best way? Is there a cheat to get around doing it so much? Thanks, Cyric

##### Share on other sites
Not really, if you are having performance issues with a 2D space sim you should probably be looking at the bigger picture. There may be some other areas you can improve performance on, quadtrees perhaps? i don't know what is causing the problems but i'm sure there are other areas that you should think about optimising first.

The only trick with distances that i can think of is that if you are just comparing distance, you can compare the distances squared which avoids using the square root function. But you probably already knew that.

##### Share on other sites
One optimization that can often be done is to simply not do the square root. Use this when all you care about is comparing two distances to each other to see which one is larger. In this situation, the square root is absolutely useless, as it doesn't change the result of the comparison.

Me.Slow == true[/edit]

##### Share on other sites
x = x1-x2;
y = y1-y2;
return sqrt(x*x + y*y);

Just shaved off 2 subtracts

##### Share on other sites
Quote:
 Original post by Raymond_Porter420Just shaved off 2 subtracts

Common subexpression elimination.

##### Share on other sites
Cool. I did not know that.

##### Share on other sites
to increase speed u can remove the square root and work with higher values [smile]

##### Share on other sites
Quote:
 Original post by DevLiquidKnightto increase speed u can remove the square root and work with higher values [smile]

They won't necessarily be higher: sqrt(x) > x is true for any x < 1.0

##### Share on other sites
I would suggest returning float (not double) and inlining it. A good compiler should eliminate the common sub expressions without creating the 2 extra variables.

I always...when in doubt cheat by looking at what the compiler actual does by examining the output .asm or .cod files.

##### Share on other sites
Just out of curiosity what are the circumstances by which you have to keep using the distance formule "many, many, many times per second." ?

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 31
• 16
• 11
• 10
• 12
• ### Forum Statistics

• Total Topics
634117
• Total Posts
3015601
×