Friday, September 30, 2011

Android Bitmap heap

If you have been developing an app for Android that uses a lot of Images (I wonder which app does not), then very likely you have faced
OutOfMemoryError: bitmap size exceeds VM budget.
Then you probably tried to see who is using memory using DDMS and got a big surprise that heap size usage is much smaller than you expected. It could be that you saw the app heap was less than 4MB when you got out of memory error.

The interesting fact is, Android decided to handle the bitmaps differently in memory. The bitmap pixel data were not stored in java application heap, but rather in native memory. That's why those big chunks of data were not shown in the heap. Although when android is calculating the max allowed memory, it is counting those native memory allocations (and you get OutOfMemoryError even when heap is not full).

Although the pixel data are stored differently, typically you don't need to free those memory manually. If no one is referencing to the bitmap, pixel data will be automatically cleared up with the bitmap in next garbage collection cycle. Advanced developers can use
method to clear those. Recycle does not clear the native memory immediately, rather marks it for garbage collector, so that on next gc run it's cleared.

Good news is things have changed at Honeycomb. Honeycomb onwards bitmap payloads are stored in the heap, as you would normally expect. Ahh, it's so nice to debug stuffs and see exactly how the memory is being consumed by those bitmaps.

No comments:

Post a Comment