Reputation: 123
Android uses the RectF structure for drawing bitmaps. I am working on my game structure, so for example, a Sprite will have and x/y coordinate, width, height, speed, and so on. This means every time in my render loop I have to cast those integers to floats when figuring out the source/target RectF's to use... alternatively, I can be far more universal and use floats everywhere so that when it comes time to simulate the physics and render, all of the types are already of the same type... even if it is unnecessary for what the property is (I don't need a float for "x position", but will have to cast it when rendering if not).
if floats generally are 2-10x's more ineffient (per http://developer.android.com/guide/practices/performance.html), what is the proper course to take?
TLDL: Should I cast int's to float on render, or just have all of the contributing variables be floats to begin with, even if floats are inefficient? How inefficient is a typecast?
Upvotes: 12
Views: 426
Reputation: 1898
The best way to do this is to do your calculations with the highest degree of precision required to produce the expected results within the specified tolerance. That means if you need to use doubles to do calculations and get the expected results with consistency, then use them. Figure out where less precision is acceptable, and only do the operations that require it with floats. Remember, your world doesn't have to approximate earth gravity for falling objects, you could simplify things and make the gravity 10 instead of 9.81, make pixels correspond to even units, etc. It'll also help if you define your constants in the same units and avoid doing unit conversion to do math (as this results in extra ops), it's better to add more final constants that have something like gravity in cm/s, m/s and km/h than it is to only have one and to convert it a thousand times. Oh and the cost of casting int to float isn't very high compared multiplying 2 floats, so think about that.
I'll also note that FPUs are becoming more and more common in modern android phones, and so the issue of using floating point math is becoming a little less important (although not entirely).
The other thing I want to note is Double/Float/Integer vs. double/float/int. The former require new objects to be created to use and shouldn't be used for math (whenever possible), whereas the latter are primitives and do not result in new object creation to use, they're less costly to create.
Upvotes: 5