Android Perf Patterns - Skim 1 - Memory

The Android Developers Youtube Channel is putting up so much valuable information regarding Android development. One of their best series is the Android Performance Patterns Series which focuses on helping developers write faster and more performant Android applications. At the time of writing, it already has 5 hours of jam-packed content in 73 videos.

In the first installment of several skims, I’ll summarize the content of the first five episodes of season 1 which is all about memory.

Memory

Some Theories

Fix Them Leaks!

To check for GC event issues:

To detect and fix memory leaks:

Assume we have an activity that has bitmaps that have to be GCed after the activity is destroyed:

  1. Create a blank activity with a low or known memory allocation and create a way for the bitmap activity to transition into it.
  2. Use the Heap Viewer to get a snapshot of how memory normally looks like in the activity that has bitmaps.
  3. Transition into the blank activity and click “Cause GC” to force garbage collection which should remove allocations from the bitmap activity.
  4. Once you’re in the blank activity, do another heap dump and inspect if there are allocations that shouldn’t be there.
  5. If there are suspects, switch to the Allocation Tracker tool to know what allocations are occurring.
  6. To use allocation tracker, Press Start Allocation Tracking, open the bitmap activity, transition to the blank activity, press “Cause GC”, then press Stop Allocation Tracking.
  7. After a while, the tool will display a list of all objects that were created, the order in which they were created and where they were created.
  8. You can now track down the allocations on your code and figure out why they are not being freed.

To prevent memory churn:

  1. Avoid allocation in inner loops.
  2. Avoid onDraw allocations.
  3. Consider using an object pool. The pool allocates a group of objects and allows them to be grabbed and returned once usage is done. Objects are pulled from the pool instead of allocating them again on the memory heap.

References