How to determing java object size in memory efficiently?

9.1k Views Asked by At

I am using a lru cache which has limit on memory usage size. The lru cache include two data structures: a hashmap and a linked list. The hash map holds the cache objects and the linked list keeps records of cache object access order. In order to determine java object memory usage, I use an open source tool -- Classmexer agent which is a simple Java instrumentation agent at http://www.javamex.com/classmexer/.

I try another tool named SizeOf at http://sizeof.sourceforge.net/.

The problem is the performance very expensive. The time cost for one operation for measuring object size is around 1.3 sec which is very very slow. This can make the benefits of caching to be zero.

Is there any other solution to measuring a java object memory size when it is alive?

Thanks.

3

There are 3 best solutions below

0
On

Since you already have a tool that does it...the reality is that there's no fast way to do this in Java.

1
On

Look at this: How to calculate the memory usage of a Java array Maybe it helps you in the analysis.

1
On

Getting an accurate, to the byte value will be expensive as it needs to use reflection to get a nested size, but it can be done.

In Java, what is the best way to determine the size of an object?

http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html