tags:

views:

379

answers:

2

I keep hearing that Android applications should try to limit the number of objects created in order to reduce the workload on the garbage collector. It makes sense that you may not want to created massive numbers of objects to track on a limited memory footprint, for example on a traditional server application created 100,000 objects within a few seconds would not be unheard of.

The problem is how far should I take this? I've seen tons of examples of Android applications relying on static state in order supposedly "speed things up". Does increasing the number of instances that need to be garbage collected from dozens to hundreds really make that big of a difference? I can imagine changing my coding style to now created hundreds of thousands of objects like you might have on a full-blown Java-EE server but relying on a bunch of static state to (supposedly) reduce the number of objects to be garbage collected seems odd.

How much is it really necessary to change your coding style in order to create performance Android apps?

+3  A: 

I'd say that really depends on what you're doing and what your coding style is now. It's always somewhat necessary to keep in mind the hardware limitations of a mobile device and program accordingly, but then again, it's good practice to be cognisant of that no matter where your app is going to run. If you are doing a lot of really intensive calculations that need to update in real time or something like a game, then you may look into using the NDK, but if you are just doing normal user-driven stuff it shouldn't be that bad. My advice would be to try to be frugal but not worry too much about optimisation until you get a feel for how it runs.

CaseyB
+5  A: 

The "avoid allocation" advice is usually with regard to game loops. The VM has to pause to collect garbage, and you don't want that happening while your game is animating at 30fps. If you don't allocate any objects, the VM won't need to collect garbage to free memory. If you have a game that needs to run without user-visible hiccups, then you should consider changing the code in the relevant parts to minimize or eliminate allocation.

If you're making an app that holds recipes or shows photos, I wouldn't worry about it -- the GC hiccup is not something the user will likely notice.

Future improvements to the Dalvik GC (e.g. generational collection) should make this less of an issue.

fadden
I'd also add that you'll often find Java code that was original written for desktops or servers that is extremely inefficient and will thrash through a ton of objects compared to the amount of work it does. For example, I have seen networking code that is continually causing GCs as it processes data from the network. If your code is doing this, you should really look at optimizing it, not specifically because of Dalvik, but because it is not appropriate for a mobile device -- all of that extra work comes directly from the battery.
hackbod