views:

41

answers:

2

What is the proper way to measure how much memory from the heap should be used to create new object of a certain type (let's talk about Integers to keep it simple)?

Can this value be calculated without experiment? What are the rules in that case? Are these rules strictly specified somewhere or they can vary from jvm to jvm?

A: 

It could vary from JVM to JVM.

You may like this blog post from an Oracle engineer:

In the case of a Java Integer on a 32-bit Hotspot JVM, the 32-bit payload (a Integer.value field) is accompanied by a 96 additional bits, a mark, a klass, and a word of alignment padding, for a total of 128 bits. Moreover, if there are (say) six references to this integer in the world (threads plus heap), those references also occupy 192 bits, for a total of 320 bits. On a 64-bit machine, everything is twice as big, at least at present: 256 bits in the object (which now includes 96 bits of padding), and 384 bits elsewhere. By contrast, six copies of an unboxed primitive integer occupy 192 bits

Thilo
A: 

That's not easy to do in Java: sizeof does not exist and alternate solutions, such as serializing the objects into a byte stream and looking at the resulting stream's length, don't work in all cases (e.g. strings).

However, see this quite complicated implementation using object graphs.

Frédéric Hamidi
@Frederic: you've probably linked this thread in your answer by mistake:)
Roman
@Roman, whoops, mistake edited :)
Frédéric Hamidi