Skip to content

Android: allocation-free code avoids the GC freeze

When a Java program creates new objects (using new), it results in the subsequent invocation of the Garbage Collector to free up memory. On Android an invocation of the GC takes of an order of 100ms, so it produces a user-visible short freeze of the application. Especially when the application is doing some form of animation the freeze is visible. In addition the GC is expensive (CPU & battery).

In order to avoid the GC invocations one can use allocation-free code. This is code that allocates most of the needed objects up-front, once, and then keeps reusing the existing objects while in the animation loop. Of course, be careful to balance the pre-allocation and object reuse (which speeds things up by avoiding GC) with the size of the allocated objects which may increase the memory usage of the application. In general, do not keep large objects alive longer than necessary.

For example in a View you can create a Paint object once and keep reusing it for all the onDraw() calls, instead of creating one or more “new Paint()” for each onDraw(). And similarly for a Point or an array of Points, etc.

String is immutable and thus can’t be reused, but you can use StringBuilder instead, which is pretty similar to String and can be reused.

Of course, it is easier to avoid the object creations that happen in the application code and thus are visible (look for “new”); it is a bit harder to detect and avoid the allocations that happen in the framework code as they are not so obvious. You can use the ddms Android tool to track down the object creations done by an application.

After taking care to remove the object creations from the hot areas of code you may be surprised by how fast and smoothly the application runs.

Post a Comment

Your email is never published nor shared. Required fields are marked *