Using FloatMath or Math and a cast? Using FloatMath or Math and a cast? android android

Using FloatMath or Math and a cast?


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 msFloatMath.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 msFloatMath.sin(F) Total:       38 ms,     Per Op: 0.0092773 msMath.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


The docs for FloatMath say:

Math routines similar to those found in Math. Performs computations on float values directly without incurring the overhead of conversions to and from double.

and your quote says:

using android.util.FloatMath was recommended for performance reasons when operating on floats

Presumably the benefit of FloatMath was always specifically for when you want a float, but this benefit has now been negated.

So use:

float foo = (float) Math.sin(bar);

Also consider that if performance is so critical that you need to worry about this, maybe the switch to double is warranted after all (as not to incur the cost of conversion).


I was just looking into the same issue recently and found this bug report on the issue. The Math functions outperform the FloatMath ones by an order of magnitude, as shown on the quote below:

Using DDMS, I profiled the code in question. Each of the functions below were called over 100x.

       Name                 | Cpu Time / Call----------------------------------------------java/lang/Math.sin (D)D     | 0.005java/lang/Math.cos (D)D     | 0.007java/lang/Math.sqrt (D)D    | 0.004android/util/FloatMath.sin  | 0.017android/util/FloatMath.cos  | 0.017android/util/FloatMath.sqrt | 0.016

If you follow the documentation changes in the AOSP tree you'll see here that Math functions are preferred to FloatMath on versions of android with a JIT, which is basically anything from Froyo (2.2) and up.