Search code examples
androidandroid-memory

Trying to reduce app memory, what values should I log?


My app often runs out of memory. I'm working on reducing memory usage but I would like to log how much memory on average my users use, have available, etc, to see if the changes I make are having any effect on the real world.

I found these values I could capture:

long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long maxMemory = Runtime.getRuntime().maxMemory();

But I'm not certain those are the right ones. Is that freeMemory value one that would tell me if I'm likely to get an OutOfMemoryError? If not, which values should I log?


Solution

  • Is that freeMemory value one that would tell me if I'm likely to get an OutOfMemoryError?

    Probably not.

    An OutOfMemoryError will occur when you try to make an allocation and there is no free block big enough to fulfill that request, even after an emergency garbage-collection run. On Android 7.1 and older, due to the nature of the garbage collector, this can occur because your heap gets fragmented. freeMemory() indicates the sum of all free blocks, not the size of the largest free block.

    So, you need to look at the OutOfMemoryError crashes that you are getting. Typically, in Android, those will come from large allocations, such as loading a Bitmap. If that is the source of your crashes, then freeMemory() will be of little use, and there is nothing that you can log.

    If, on the other hand, you are getting crashes for fairly small allocations (say, 128 bytes and lower), then most likely you really are exhausting your heap. In this case, freeMemory() may be useful to log.