首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java中盒式原语的存储成本是多少?

Java中盒式原语的存储成本是多少?
EN

Stack Overflow用户
提问于 2012-01-27 17:29:28
回答 3查看 3.8K关注 0票数 17

java.lang.Integerjava.lang.Character这样的装箱原语在Java中有多大(以字节为单位)?

一个int是4个字节,一个典型的指针也是4个字节(如果不是被JVM压缩的话)。整数(没有缓存)的成本是这样的4 bytes + 4 bytes = 8 bytes吗?盒子对象中是否还有更多的隐藏字段或与对象相关的额外开销(例如,对于我不知道的对象是否存在一般成本?)

我对缓存问题不感兴趣。我知道JVM缓存一定范围内的整数。

人们可以重新表述这个问题:与原始值相比,用于装箱值的内存量乘以的最大因数是多少?

编辑: JVM理解存在多个实现。在典型的32位HotSpot实现中,典型的成本是多少?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-01-27 17:55:59

这是定义的实现,所以没有具体的答案。但我应该能回答热点的问题。

您需要知道的是: Hotspot总是在8字节的边界上对齐对象。此外,每个对象都有两个单词的开销。1

如果我们把这些放在一起,我们就会得到:

32位VM: 4字节整数+2字对象标头=12字节。这不是8的倍数,因此,1整数的成本是下一个8: 16字节的倍数。

64位VM: 4字节整数+2字=20字节。再次舍入:24字节大小。

显然,引用的大小与对象本身的大小无关,除非它具有对其他对象的引用,而对于简单的int包装器则不是这样。如果是这样的话,32位的引用为4字节,64位JVM为堆的为4字节,<= 32 on为4字节,而现代JVM上的CompressedOops为8字节。

有兴趣的人可以查看share/vm/oops/oop.hpp中的代码

票数 10
EN

Stack Overflow用户

发布于 2012-01-27 17:38:52

不止是这样。

每个对象引用都有额外的开销,例如类引用。不仅如此,你的4字节指针也不太准确。它是一个引用,所以它是一个ID加上一个指针,如果您在64位JVM上,这个指针可能是8个字节。

VM实现似乎也存在差异。要确定这一点,最好的方法是在剖析器中把它拉上来。

我(超级搜索)的估计是。对象引用16字节(64位JVM)类引用16字节原始值4字节(假设int)。合计。36字节

编辑:现在您指定了32位JVM,使用上面相同的数学,我的数据将是20个字节。

票数 1
EN

Stack Overflow用户

发布于 2012-01-27 18:03:30

我知道这并不能确切地回答您关于盒式原语的存储成本的问题,但是我从您的问题中感觉到,您在质疑是否需要使用它们。

以下是约书亚·布洛赫从有效Java (第2版)中摘录的一段,应该能帮助您做出决定:

"So when should you use boxed primitives? They have several legitimate uses. The first is as elements, keys, and values in collections. You can’t put primitives in collections, so you’re forced to use boxed primitives. This is a special case of a more general one. You must use boxed primitives as type parameters in parame- terized types (Chapter 5), because the language does not permit you to use primi- tives. For example, you cannot declare a variable to be of type Thread- Local<int>, so you must use ThreadLocal<Integer> instead. Finally, you must use boxed primitives when making reflective method invocations (Item 53).

In summary, use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw a NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations."

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9037468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档