Skip to content

The size of an object instance at runtime – pre Java 1.5

by Steve

In Java 1.5, Sun provides us with a miracle method that is long overdue:
long java.lang.instrument.Instrumentation.getObjectSize (Object objectToSize)

However, this is still limited in that it only returns the total size of the Object, not the details about the Object size in regard to its composition.

Enter monq.jar from
Whatizit.

There’s a Sizeof class in monq.jar with a static sizeof method that walks through an Object instance at runtime and counts up the bytes in use for all its elements and then returns a HashTable. The results seem to be consistent with what I’ve seen by using the java.lang.Runtime class to estimate heap size. The Sizeof class also provides a convenient printTypes method which can be used to dump the HashTable data to an OutputStream (such as System.out). This allows you to easily see which nodes of a given Object tree might be prone to causing trouble. Though it cannot be 100% accurate, it’s probably very close.

Here’s a simple usage example:

public void printObjectSizeTable(Object object) {
   Sizeof.printTypes(System.out, Sizeof.sizeof(object));
}

The above will print out a table consisting of four columns, which are:

  • Count of the particular type
  • Total byte size of the type
  • Containing type class name
  • Type class name

Example output using a populated ArrayList as the parameter to the method above:

26 1516 java.lang.Object; java.util.ArrayList
25 500 java.util.ArrayList java.util.ArrayList
1 20 java.util.ArrayList monq.stuff.Sizeof$Root
52 2036 TOTAL

I might just start integrating this into some junit tests. I certainly believe that it will be very useful in determining the cause of performance problems.

-”That’s all for now folks”

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

2 Comments

  1. Priyatam wrote:

    Isn’t profiler more comprehensive to use for performance, finding size of classes/instances?

    Tuesday, November 13, 2007 at 3:27 pm | Permalink
  2. eokuwwy wrote:

    While profiler and TPTP for Eclipse are highly useful tools, they serve a different purpose. I was more interested in determining size at runtime within the code, in order to direct programming logic.

    For instance, if I’m maintaining a cache of Objects that grows over time, I can set a size limit and write code to flush the cache accordingly if it reaches that limit.

    Wednesday, November 21, 2007 at 12:45 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*