Sonntag, 1. Mai 2011

Speed of java.lang.Math functions

I am currently developing a game with LWJGL, Slick and kryonet. It looks like those 3 give a really good combination for creating cross-plattform multiplayer games. You don't have to worry about a lot of stuff.

One intersting thing I found out yesterday is that you should always use methods provided by the JDK itself. It sounds obvious, but it is not always so easy to find those. For calculating distances in my game (2D game by the way) I used the good ol' pythagoras. You remember: a²+b²=c². So the distance would be the square root of c. In java it looks like this:

float distance = (float) Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2));

I cast it to float, because my game has to send a lot of information over the network and the accuracy of float is sufficient.
This is the way I did it before. After a lot of objects appeared that have to calculate distances appeared on the screen my game got really slow, so I wondered if there was a faster way to achieve the same calculation - and there is: java.awt.geom.Point2D

This abstract class has childs of every datatype implementing the class. java.awt.geom.Point2D.Float is what I used then. The above calculation looks like this now:

Float p1 = new Float(x1, y1);
Float p2 = new Float(x2, y2);
float distance = (float) p1.distance(p2);

We don't use any slow java.lang.Math functions anymore - instead we use the optimized distance method. To give you some numbers, I wrote 3 JUnit methods to measure the time. The first gets random numbers, the second calculates the distance with the Math-library and the third uses the distance method.
Generation of 4x1 Million random float numbers: 0,182 s
Calculating the distance with java.lang.Math: 0,109 s
Calculating the distance with the distance-method: 0,036 s

Initial Post

Hello,

my name is Klaus Pfeiffer and with this blog I want to give back some of my knowledge to the JAVA community. I for myself found a lot of information on blogs and forums, so I hope this blog is of some interest and help for you.

Kind regards,
- Klaus