Java中为一个Integer对象分配多少内存?如何找出任何自定义对象的这个值?

衡量应该使用堆中多少内存来创建特定类型的新对象的正确方法是什么(让我们谈谈整数以保持简单)?

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)?

这个值可以不用实验计算出来吗?这种情况下的规则是什么?这些规则是否在某处严格指定,或者它们可能因 jvm 而异?

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?

推荐答案

它可能因JVM而异.

您可能会喜欢 Oracle 工程师的这篇博文:

You may like this blog post from an Oracle engineer:

对于 32 位 Hotspot JVM 上的 Java Integer,32 位有效负载(Integer.value 字段)伴随着 96 个附加位、一个标记、一个 klass 和一个对齐填充字,总共 128 位.此外,如果世界上有(比如说)六个对该整数的引用(线程加堆),那么这些引用也占用 192 位,总共 320 位.在 64 位机器上,一切都大了一倍,至少目前是这样:对象中有 256 位(现在包括 96 位填充),其他地方有 384 位.相比之下,一个未装箱的原始整数的六个副本占用 192 位

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

相关文章