Android & Dalvik - Get the size of an object

前端 未结 3 1749
一整个雨季
一整个雨季 2020-12-28 16:12

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

相关标签:
3条回答
  • 2020-12-28 16:37

    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.

    0 讨论(0)
  • 2020-12-28 16:38

    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

    0 讨论(0)
  • 2020-12-28 16:51

    For this problem, it is better not to use a programatic approach but to use the Memory Analyzer Tool (MAT) from www.eclipse.org/mat/ 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.

    0 讨论(0)
提交回复
热议问题