Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

memory - What is the storage cost for a boxed primitive in Java?

How large, in bytes, is a boxed primitive like java.lang.Integer or java.lang.Character in Java?

An int is 4 bytes, a typical pointer is also 4 byte (if not compressed by the JVM). Is the cost for an Integer (without caching) thus 4 bytes + 4 bytes = 8 bytes? Are there any more hidden fields within the box-object or additional overhead incurred regarding objects (i.e. is there a general cost for objects that I'm not aware of?).

I'm not interested in caching issues. I know that Integers within a certain range are cached by the JVM.

One could rephrase the question: What is the maximum factor to be multiplied on the amount of memory used for boxed values versus primitive values?

EDIT: I do understand that multiple implementations of the JVM exist. What is the typical cost in a typical 32-bit HotSpot Implementation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is implementation defined, so there's no specific answer. But I should be able to answer it for Hotspot.

What you need to know is: Hotspot always aligns objects on 8byte boundaries. Furthermore there are 2 words overhead for each and every object. [1]

If we put this together we get:

32bit VM: 4byte integer + 2 words object header = 12bytes. That's no multiple of 8 so as a result the cost for 1 integer is the next multiple of 8: 16byte.

64bit VM: 4byte integer + 2 words = 20bytes. Rounding up again: 24byte size.

The size of a reference obviously does not play into the size of an object itself, except if it has references to other objects which isn't the case for a simple int wrapper. If it would, we'd have 4byte per reference for 32bit and 4byte for heaps <= 32gb with CompressedOops on modern JVMs (otherwise 8byte) for 64bit JVMs.

[1] Interested people can look at the code in share/vm/oops/oop.hpp


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...