1

Is it possible to check programatically how much memory takes some object (with the whole subtree in the JVM memory). I would like to say (from the java code)

'tell me how much memory in the current JVM takes the JPanel with the whole reference subtree when we assume that mentioned JPanel is the root of this tree'.

I wonder if I could this way compare how much memory take two JPanels (or JFrame or whatever), and which takes more - without analyzing the dump. And I wonder if the answer is 'yes' how precise would be this value.

Łukasz Rzeszotarski
  • 5,791
  • 6
  • 37
  • 68
  • 1
    It's not a tree, it's a graph. –  Aug 23 '13 at 13:14
  • Suppose you can do that. How will you deal with aliasing? e.g., if `obj1` and `obj2` both point to common objects in the graph, it'd be misleading to count those twice. – C. K. Young Aug 23 '13 at 13:14
  • @delnan Jinx! (re graph) – C. K. Young Aug 23 '13 at 13:14
  • true but I would like to more less say (quite precisely - but not exactly of course) how much memory take the object and other objects which were created 'by this object' - so if I have a JFrame and this JFrame is composed of two JPanels, and each JPanel is composed of two JButtons I would like to know how much memory take 'JFrame + 2 * JPanel + 4 * JButton' – Łukasz Rzeszotarski Aug 23 '13 at 13:18
  • Take a [profiler](http://jyops.blogspot.de/2012/09/java-memory-model-simplified.html), try to figure out an estimation and somehow implement that in your code – zapl Aug 23 '13 at 13:19
  • @zapl - there are libraries that will do the estimation for you. – radai Aug 23 '13 at 13:24
  • 2
    You should note that all the gui components are proxies for native components which do the real displaying. Any tools you use will give the space used n the heap, not the native objects it proxies. – Peter Lawrey Aug 23 '13 at 13:40

2 Answers2

3

as stated in the comments to your qustion, the sizeOf problem in java isnt easy to solve, not only because the object youre trying to size isnt really the root of a memory graph, but also because there are issues with counting the size of static fields etc (they belong to the whole class, not any specific instance).

however, there are ways to get some meaningful data.

the 1st approach is to use a java agent attached to the jvm which in turn calls a size estimation function that sun/oracle have added starting with java 6. see this page for instructions

the 2nd approach is to estimate the size of an object tree based on theoretical calculations. there's a library that does this for you here

radai
  • 23,949
  • 10
  • 71
  • 115
1

You can check JAMM, which is a java agent for measuring object size. You can find a tutorial here how to use it.

Katona
  • 4,816
  • 23
  • 27