There are two basic rules for resource-constrained systems:
- Don't do work that you don't need to do.
- Don't allocate memory if you can avoid it.
All the tips below follow from these two basic tenets.
Some would argue that much of the advice on this page amounts to "premature
optimization." While it's true that micro-optimizations sometimes make it
harder to develop efficient data structures and algorithms, on embedded
devices like handsets you often simply have no choice. For instance, if you
bring your assumptions about VM performance on desktop machines to Android,
you're quite likely to write code that exhausts system memory. This will bring
your application to a crawl — let alone what it will do to other programs
running on the system!
That's why these guidelines are important. Android's success depends on
the user experience that your applications provide, and that user experience
depends in part on whether your code is responsive and snappy, or slow and
aggravating. Since all our applications will run on the same devices, we're
all in this together, in a way. Think of this document as like the rules of
the road you had to learn when you got your driver's license: things run
smoothly when everybody follows them, but when you don't, you get your car
Before we get down to brass tacks, a brief observation: nearly all issues
described below are valid whether or not the VM features a JIT compiler. If I
have two methods that accomplish the same thing, and the interpreted execution
of foo() is faster than bar(), then the compiled version of foo() will
probably be as fast or faster than compiled bar(). It is unwise to rely on a
compiler to "save" you and make your code fast enough.