Calculating byte-size of Java object

codeObserver picture codeObserver · Oct 21, 2010 · Viewed 14.6k times · Source

I am working on calculaitng the size [memory used] of a java object [hashmap] . It contains elements of different data types [at runtime] so [ no-of-elem * size-of-element] is not that good an approach. The code right now does it by series of

if (x)
  do something
else if (primitives)
  lookup size and calculate

However this process is a CPU hog and in-efficient.

I am thinking of following 2 approaches instead:

  1. Serialize the object to a buffer and get the size.
  2. Look into java.lang.instrument to get the size

I am looking for anyones experience with these approaches for performance , efficiency, scaling etc OR if you know any better way.

P.S: This is a background utility that I am building so the size need no be super accurate though it should be about correct. So I am willing to trade accuracy for performance

I am not interested in the deep-size [the size of objects that are refered by this object will not be computed.]

I am looking for a performance comparisons and understanding how getObjectSize() works internally ..so that I do not messup something else to improve the performance

Thanks

Answer

Mihir Mathuria picture Mihir Mathuria · Oct 21, 2010

Use getObjectSize() method of the Instrumentation package.

Look here for implementation details: