2

I'm implementing a caching system for android app, I need to add a parameter that specify the maximun amount of memory permited for caching, but I don't know how to calculate the memory used for an object.

luisZavaleta
  • 1,160
  • 11
  • 21
  • 1
    possible duplicate of [In Java, what is the best way to determine the size of an object?](http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object) – ZoogieZork Apr 27 '11 at 19:03

3 Answers3

1

Apparently 1.5 added an instrumentation interface. Check out this article

http://www.javapractices.com/topic/TopicAction.do?Id=83

you can use a getObjectSize() method. Its implementation specific and an approximation but better than nothing

nsfyn55
  • 14,875
  • 8
  • 50
  • 77
  • 2
    It is a good option but not for android :'( "The java.lang.instrument package was removed from dalvik core library, because this package makes a fundamental assumption that the execution format being used by the VM is a .class file. .class files do not appear on Android at all. " http://groups.google.com/group/android-developers/browse_thread/thread/311e16daba10dd7c – luisZavaleta Apr 27 '11 at 19:33
  • check this post out http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object One of the guys says there may be a C-like sizeOf() implementation floating around – nsfyn55 Apr 27 '11 at 20:26
  • 1
    sizeOf uses Internally java.lang.instrument http://www.google.com/codesearch/p?hl=en#JJilFFvKD1Y/trunk/Java/%E4%BE%8B%E5%AD%90/SizeOf/src/net/sourceforge/sizeof/SizeOf.java&q=net.sourceforge.sizeof.SizeOf&d=8 – luisZavaleta Apr 28 '11 at 00:29
  • http://www.javaworld.com/javaworld/javatips/jw-javatip130.html - This is what I was referring to. Its old as dirt and probably not particularly useful because it relies are triggering garbage collection which is unreliable at best and comparing heap sizes. I'm not sure there is a good way to do this if you can't use the Intstrumentation stuff – nsfyn55 Apr 28 '11 at 12:36
0

You can consider getting a heap dump of the application and observing its Retained Heap

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • To produce a heap dump use heapViewer (since JDK5.0). It is located in %JDK_HOME%\demo\jvmti\heapViewer You can start the feature from the command line with th -agentlib option. You can trigger the dump with a Ctrl-C or Ctrl-\ (SIGQUIT). – this.josh Apr 28 '11 at 17:40
-1

It depends on the object. Calculate how much memory each part of the object takes when allocated to get a baseline for the max size the object can be.

buddyp450
  • 528
  • 2
  • 10
  • 27