Thursday 21 July 2011

Caculating the size of a graph of objects in Java

Finding out the actual size of an object in memory is not easy in Java. In C there is a trivial sizeof operator that will tell you, not so in Java. One has to go to the length of using a javaagent (see for example stackoverflow's discussion on this) or play around with Runtime#freeMemory and Runtime#gc() and hope that garbage collection is in any shape, form or way reliable.

Even harder is the question of how much memory a complete structure or graph of objects consumes. For example, how large is that big HashSet of Strings that I just created? There appears to be no built in support for that. However, with Instrumentation#getObjectSize and a bit of reflection this can be determined in a relatively small amount of code, which I have put on Gist.

Results on a Java 6 Mac OS JVM: empty HashSets take 144 bytes, putting a string like "string" in it shoots up to 256 bytes, adding the ubiquitous "hello world" gets us to 360 bytes and so forth. A rather staggering amount of memory all in all. Best not to look too deeply into this ...

No comments:

Post a Comment