Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perf: extend Coordinate with distanceSq and distance3DSq #175

Open
jandam opened this issue Sep 18, 2017 · 6 comments
Open

Perf: extend Coordinate with distanceSq and distance3DSq #175

jandam opened this issue Sep 18, 2017 · 6 comments
Milestone

Comments

@jandam
Copy link

jandam commented Sep 18, 2017

This is simple optimization to avoid computing Math.sqrt during finding minimal distance.
Suggested method can be used for example in LineSegment, Triangle, InteriorPointPoint, InterirorPointLine, , LineString::equalsExact(Geometry other, double tolerance)

 public double distanceSq(Coordinate c) {
    double dx = x - c.x;
    double dy = y - c.y;
    return dx * dx + dy * dy;
  }

  public double distance3DSq(Coordinate c) {
    double dx = x - c.x;
    double dy = y - c.y;
    double dz = z - c.z;
    return dx * dx + dy * dy + dz * dz;
  }
@dr-jts
Copy link
Contributor

dr-jts commented Sep 18, 2017

Interesting. Is the use of Math.sqrt() a significant performance hit?

@jandam
Copy link
Author

jandam commented Sep 18, 2017

I didn't make any benchmarks. It's just very simple micro optimization used in games. Computing min distance is O(n). And we can compute Math.sqrt only once.

@dr-jts dr-jts added this to the FUTURE milestone Sep 18, 2017
@dr-jts
Copy link
Contributor

dr-jts commented Sep 18, 2017

I think I'd prefer to name these distanceSqr and distanceSqr3D

@jandam
Copy link
Author

jandam commented Sep 19, 2017

Yes it's better. English is not my native language. So method names are up tu you.

@jnh5y
Copy link
Contributor

jnh5y commented Oct 28, 2017

I'd agree that comparing and minimizing the square of the distances is a typical trick to save some cycles. I'm +1 on it.

@FObermaier
Copy link
Contributor

DistanceSquared.pointToPoint(Coordinate, Coordinate) is part of #427.
But not as a member of Coordinate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants