In the latest update of the Android API the FloatMath
is marked with the following lint-warning:
In older versions of Android, using android.util.FloatMath was recommended for performance reasons when operating on floats. However, on modern hardware doubles are just as fast as float (though they take more memory), and in recent versions of Android, FloatMath is actually slower than using java.lang.Math due to the way the JIT optimizes java.lang.Math. Therefore, you should use Math instead of FloatMath if you are only targeting Froyo and above.
It is also mentioned here that double and float are equal in speed on recent hardware.
I am using some trigonometric math in an application I am currently working on (targeted Froyo and above), but high precision is not needed, so I have been using floats and FloatMath
so far, and there is no need whatsoever to switch to doubles.
However, the "use Math
over FloatMath
"-recommendation does not say which one to use if float is the desired result.
So, in short; which one is preferable?
float foo = FloatMath.sin(bar);
or
float foo = (float) Math.sin(bar);
On a side note, I only have a Froyo-device, so I can't really do any proper benchmarking on my own.
As of API level 22 the FloatMath-class has been deprecated in favor of the regular Math-class.
As you can see from the results below, using java.lang.Math is faster for floats than for doubles, and faster than FloatMath. Furthermore, FloatMath has no .exp() or .pow() prior to API level 17.
On a Samsung GT_i9295 (4.2.2), 2^24 cycles
Math.exp(D) Total: 7405 ms, Per Op: 0.0004414 ms
(F)Math.exp(F) Total: 5153 ms, Per Op: 0.0003071 ms
FloatMath.exp(F) Total: 8533 ms, Per Op: 0.0005086 ms
No data for Math.sin on the samsung because it has randomly decided to ignore Log.d() >:(
On a HTC Hero_HT99VL (2.3.7), 2^12 cycles
Math.sin(D) Total: 42 ms, Per Op: 0.0102539 ms
(F)Math.sin(F) Total: 33 ms, Per Op: 0.0080566 ms
FloatMath.sin(F) Total: 38 ms, Per Op: 0.0092773 ms
Math.exp(D) Total: 56 ms, Per Op: 0.0136719 ms
(F)Math.exp(F) Total: 47 ms, Per Op: 0.0114746 ms
FloatMath.exp(), .pos() and .hypot() require API level 17