Best Practices

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

  • The garbage collector is your biggest enemy. Once it obtains CPU time for doing its dirty work, it will stop the world for up to 600 ms. That's half a second that your 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 that 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; instead, use the SparseArray class provided by the Android API. Use StringBuffers instead of concatenating strings with the + operator. This 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. Perhaps you should avoid getters and setters as well. Direct field access is about three times faster than method invocations without the JIT, and about seven times faster with the JIT. Nevertheless, think of your design before removing all your getters and setters.
  • 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, 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.

Of course, you need to be careful about many other things. We'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!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset