Axl
Axl

Reputation: 4891

best way to measure java object(s) footprint in memory

Plain stupid question. I have a collection that contains java objects. These objects are not instances of the same class, but they implement the same interface and conceptually very "alike" so that their sizes should be pretty similar. I need to understand approximately how much space this collection will consume in memory. What would be the easiest (best) approach to calculate that?

I understand that I can take each java class that can reside in collection, calculate their sizes (deep size, Reflection, etc.), get average, multiply by N (collection size) and get the final value.

But can that be done going the other way around - calculating the size of existing collection (without diving in Reflection, field sizes, etc)? I understand that serializing the collection to byte stream and mesuring the output size won't work because serialization will not reflect the exact object memory layout. But maybe there are other ways to do it?

Upvotes: 1

Views: 635

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533472

If you use a profiler like YourKit it can tell you the deep size of an object. You can use Instrumentation.getObjectSize() but its a real pain to use (and it only gives you the shallow size)

The best approach may be to estimate/calculate it yourself. Add up the size of each of the fields (round up to the next 8 bytes) add 12 bytes of overhead per object or 16 bytes if you are using a 64-bit JVM and Compresses Oops is off.

Upvotes: 1

Related Questions