Phil
Phil

Reputation: 3520

How to test how many bytes an object reference use in Java?

I would like to test how many bytes an object reference use in the Java VM that I'm using. Do you guys know how to test this?

Thanks!

Upvotes: 8

Views: 7307

Answers (4)

squawknull
squawknull

Reputation: 5192

If you need to be fairly accurate, check out the Instrumentation framework.

Upvotes: 2

Matt
Matt

Reputation: 11

This one is the one I use. Got to love those 16-byte references ! alphaworks.ibm.heapanalyzer

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533660

Taking the question literally, on most JVMs, all references on 32-bit JVMs take 4 bytes, one 64-bit JVMs, a reference takes 8 bytes unless -XX:+UseCompressedOops has been used, in which case it takes 4-bytes.

I assume you are asking how to tell how much space an Object occupies. You can use Instrumentation (not a simple matter) but this will only give you a shallow depth. Java tends you break into many objects something which is C++ might be a single structure so it is not as useful.

However, ifyou have a memory issue, I suggest you a memory profiler. This will give you the shallow and deep space objects use and give you a picture across the whole system. This is often more useful as you can start with the biggest consumers and optimise those as even if you have been developing Java for ten years+ you will only be guessing where is the best place to optimise unless you have hard data.

Another way to get the object size if you don't want to use a profiler is to allocate a large array and see how much memory is consumed, You have to do this many times to get a good idea what the average size is. I would set the young space very high to avoid GCs confusing your results e.g. -XX:NewSize=1g

Upvotes: 13

Mike Samuel
Mike Samuel

Reputation: 120526

It can differ from JVM to JVM but "Sizeof for Java" says

You might recollect "Java Tip 130: Do You Know Your Data Size?" that described a technique based on creating a large number of identical class instances and carefully measuring the resulting increase in the JVM used heap size. When applicable, this idea works very well, and I will in fact use it to bootstrap the alternate approach in this article.

Upvotes: 2

Related Questions