Java 中对象的内存开销是多少?

发布于 2024-07-16 18:19:50 字数 307 浏览 4 评论 0原文

复制:

一个对象的内存消耗是多少Java?

假设 Intel 或 AMD 机器上的 64 位 Linux 上有 Java 1.6 JVM,创建一个简单的对象会使用多少内存开销(以字节为单位)? 例如,二维数组中的每一行都是一个单独的对象。 如果我的阵列很大,我将使用多少 RAM?

Duplicate:

What is the memory consumption of an object in Java?

Assuming Java 1.6 JVM on 64-bit Linux on an Intel or AMD box, creating a simple object uses how much memory overhead in bytes? For example, each row in a 2-dimensional array is a separate object. If my array is large, how much RAM will I be using?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡紫姑娘! 2024-07-23 18:19:50

这取决于您使用的 JVM。

假设您没有使用带有压缩指针的 JVM,该数组将消耗:

  • 类型指针 8 个字节。
  • 数组长度为 4 个字节。
  • 数组中的每个元素 8 个字节(这些是指向实际对象的指针)。
  • 总和:8+4+len*8 字节
  • 对于具有压缩指针的 JVM:4+4+len*4 字节

然后,您在数组中存储(引用)的实际对象将消耗内存,具体取决于它们是什么类型的对象。 java.lang.Object 仅包含指向该类的指针,因此为 8 个字节,如果使用压缩指针则为 4 个字节。

对于您自己的类,您可以通过查看类中的字段来计算内存使用情况。
每个引用将消耗 8 个字节(压缩指针为 4 个字节)。 每个long 8个字节,int 4个字节,char/short 2个字节,byte/boolean 1个字节。 但所有这些都将对齐到 4 或 8 字节的倍数的偶数总大小,具体取决于您使用的 JVM。

That will depend on which JVM you use.

Assuming that you are not using a JVM with compressed pointers the array will consume:

  • 8 bytes for the type pointer.
  • 4 bytes for the array length.
  • 8 bytes for each element in the array (these are pointers to the actual objects).
  • Sum: 8+4+len*8 bytes
  • For a JVM with compressed pointers: 4+4+len*4 bytes

Then the actual objects that you store (references to) in the array will consume memory depending on what kind of objects they are. java.lang.Object only contains a pointer to the class, so 8 bytes, or 4 bytes if using compressed pointers.

For your own classes you can count the memory use by looking at the fields in the class.
Each reference will consume 8 bytes (4 bytes for compressed pointers). Each long 8 bytes, int 4 bytes, char/short 2 byte, byte/boolean 1 byte. But all these will be aligned to an even total size that is a multiple of either 4 or 8 bytes, depending on which JVM you use.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文