Best Practices

Android (or rather Dalvik) has some strange performance characteristics at times. To round of this chapter, I'll present to you some of the most important best practices you should follow to make your games as smooth as silk.

The garbage collector is your biggest enemy. Once it gets CPU time to do its dirty work, it will stop the world for up to 600 ms. That's half a second that our game will not update or render. The user will complain. Avoid object creation as much as possible, especially in your inner loops.

Objects can get created in some not-so-obvious places, which you'll want to avoid. Don't use iterators, as they create new objects. Don't use any of the standard Set or Map collection classes, as they create new objects on each insertion; use the SparseArray class provided by the Android API instead. Use StringBuffers instead of concatenating strings with the + operator. That will create a new StringBuffer each time. And for the love of all that's good in this world, don't use boxed primitives!

Method calls have a larger associated cost in Dalvik than in other VMs. Use static methods if you can, as those perform best. Static methods are generally regarded as evil, much like static variables, as they promote bad design. So try to keep your design as clean as possible. You should maybe avoid getters and setters as well. Direct field q access is about three times faster than method invocations without the JIT, and about seven times faster with the JIT. Again, think of your design before removing all your getters and setters, though.

Floating-point operations are implemented in software on older devices and Dalvik versions without a JIT (anything before Android version 2.2). Old-school game developers would immediately fall back to fixed-point math. Don't do that either, since integer divisions are slow as well. Most of the time you can get away with floats, though, and newer devices sport floating-point units (FPUs), which speed things up quite a bit once the JIT kicks in.

Try to cram frequently accessed values into local variables inside a method. Accessing local variables is faster than accessing members or calling getters.

There are of course more things we should be careful with. I'll sprinkle the rest of the book with some performance hints when the context allows it. If you follow the preceding recommendations, you should be on the safe side. Just don't let the garbage collector win!

0 0

Post a comment