java – Android & Dalvik – Get the size of an object-ThrowExceptions

Exception or error:

As we all know Java 5 introduced the ability for Instrumentation to get the size of an object with ease. Is there such a method on Android and Dalvik?

The java.lang.instrument package is not available on Android.

How to solve:

For what it’s worth, I have looked at the Dalvik VM source code and can not find any stable API to get the size of an Object. If you want to take a look yourself, the size of an object is stored in ClassObject::objectSize : size_t, see dalvik/vm/oo/Object.h.

There is, however, internal APIs to get the size of an Object. It is used by DDMS to report detailed information about object sizes. But, since the API is internal, it is likely to change between different versions of Android. Plus, the API is sends raw byte[] data around, and is client/server based and not a simple library call, so it will be extremely awkward to use. If you want to take a look, start in dvmAllocObject() in dalvik/vm/alloc/Alloc.cpp and the dvmTrackAllocation() call.

To sum it up: there is unfortunately not any readily usable, stable API to get the size of an Object in the Dalvik VM.


For this problem, it is better not to use a programatic approach but to use the Memory Analyzer Tool (MAT) from It has both standalone version and plugin for Eclipse. With it you can create a snapshot of Dalvik heap and then you could sort the list of objects by their size or also by the size of their referenced objects (retained size). I used this exactly for troubleshooting a bitmap cache leaks.


My idea to get the size of a ArrayList<String> on the heap was to serialize the object into a Byte-Array, where the lengths is the size.

I’ve used the SerializationUtils from Apache Commons Lang.

To serialize:

byte[] data = SerializationUtils.serialize((Serializable) arrayList);

The lenght of the data array should be approximately the size in bytes on the heap.

As mentioned, this requires Commons Lang library. It can be imported using Gradle:

api 'org.apache.commons:commons-lang3:3.5'

more ways mentioned here

Leave a Reply

Your email address will not be published. Required fields are marked *