Java math performance
Java 1.6 on an x86 (Intel Core 2 Duo in this case), how much faster are the 4 basic math operations +-*/ when it comes to integer vs floating point operations? We’ve all been taught that integer operations are vastly faster than floating point operations, but that was probably only true when you were taught that back in school.
Now a days 32-bit floating point operations are on par with their integer counter parts. Most modern processors can do most floating point operations in an single instruction, just like integers.
I wrote a micro benchmark doing the same operation 4,000,000 times on the same set of vectors and here are the results in milliseconds:
client + - * / sqrt sin cos integer 16 16 15 26 long 30 30 30 120 float 15 15 16 30 double 29 26 27 52 242 4205 4205 fixed 13 12 40 191 427 60 59
Fixed is fixed-point library I am testing. The fixed point sin/cos functions are so fast, since they are pre-calculated tables at start-up. On the other hand, Java’s sin/cos functions are abysmal. Java has strict requirements on sin/cos functions and this issue has been brought up as bug 5005861. This is probably one of the last major Java performance issue. If you need a fast sin, then approximate it.
The table above shows there is no performance difference between integers/floats and longs/doubles, except that double’s divide is faster than long’s!
The above was running without the -server flag. Below we have the flag turned on.
server + - * / sqrt sin cos integer 21 115 14 21 long 24 25 25 106 float 12 12 12 29 double 24 24 25 54 87 3317 3260 fixed 14 13 32 189 314 57 64
With the server flag turned on, there is some performance issues at the start of the benchmark, which erroneously shows integer addition and subtracting being worst than with the server flag turned off. I believe this is just a loading issue, and in the real world you’ll see performance at the same level as multiplication. One very interesting data point is Math.sqrt is much faster with the server flag on. This benchmark shows an improvement of almost 3x!
I would say it is probably safe for everybody to use doubles for math intensive applications. I not saying just use doubles everywhere, floats and doubles have their pitfalls as well, but that is for another article (the one sentence summary is “Time and money are valuable, so don’t use a float or double to represent it!”) Performance wise, don’t fret it, go double.


























