Pages

Sunday, December 4, 2011

Total/Free memory on android apps and games

Yesterday I was helping out my friend Sergio with his own Android game, and he needed to how much memory does each android device have, and how much memory is the app using. After checking out the biggest source of wisdom (yes, stackoverflow), this seems to be the solution:

Heap size:
long heapSize = Debug.getNativeHeapSize();
The heap size is not exactly the memory that your app is directly using, but the memory that the VM is reserving for your app. It may be slightly higher than the memory that your app is using due to fragmentation and provision. This number will vary as you allocate memory and force the VM to grow the heap to fit the extra needs.

Allocated size:
long allocated = Debug.getNativeHeapAllocatedSize();
The allocated size is the actual memory amount that your app is directly using.

Free size:
long free = Debug.getNativeHeapFreeSize();
The free size is the amount of memory from the heap that is not being used, because of fragmentation or provision.

These three measurements are very useful. Of course, the first one is the more important one, because it tells you if you are approaching the memory limit or not, but the other two are very interesting for performance reasons. If you use to have a lot of free memory in the heap (say, more than 100KB), this could be a symptom that your app is allocating and freeing a lot of memory on a regular basis, and this may lead to performance problems due to involving the garbage collector all the time.

Ok, this tells you how much memory you are using, but now there is another interesting question left: How much memory are you allowed to use? It actually doesn't depend on the physical memory amount, but in a hardwired limit that vary from device to device.

Memory limit:
long maxMem = Runtime.getRuntime().maxMemory();
This memory limit will tell you how much memory your app can allocate. In my device it is as little as 18MB. And the biggest EggSavior Level is using 13.5MB. There is room for slightly bigger levels!

I hope this brief article will shed some light to other Android game developers.

No comments:

Post a Comment