adamleesaintfrancis / spacewar

Automatically exported from code.google.com/p/spacewar
0 stars 0 forks source link

Spacewar spends 60% of its time inside constructor of Vector2D #16

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
While investigating another issue, I ran the ladder through the Netbeans 6
profiler.  I was surprised to see that the program spent 60% of it's time
inside Vector2D(float x, float y) constructor.  Practically all of this
time was spent in Math.hypot calculating the vector's magnitude.  What's
more, most of the time, that magnitude is never used.  

Furthermore, after doing some research online, I discovered that Math.hypot
is around 20 time slower than Math.sqrt(x*x+y*y).
This is because Math.hypot ensures that x*x+y*y will not overflow or
underflow before the square root is applied.  Fortunately, the scale of
Spacewar is such that we shouldn't have to worry about overflows or
underflows.  In fact, the Vector2D.dot function already does an unchecked
x*x+y*y.

Attached is a patch that fixes these issues.  It removes the magnitude
field, and instead calculates the magnitude whenever getMagnitude is called
using Math.sqrt(x*x + y*y).  While this means the magnitude of the same
vector could possibly be calculated more than once, I think this happens
seldom enough that it shouldn't be a problem.  If it does become an issue,
it's a small matter to change it so it calculates and caches it the first
time getMagnitude is called and simply returns the cache every other time.

In my tests, these changes result in a unilateral 10x performance gain,
even with clients that make heavy calculations every turn.

Original issue reported on code.google.com by ztidw...@gmail.com on 6 Apr 2008 at 3:11

Attachments:

GoogleCodeExporter commented 9 years ago
Thank you for the detailed analysis and patch!

Original comment by jfa...@gmail.com on 7 Apr 2008 at 3:31