Java 中对象的内存开销是多少?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/726404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the memory overhead of an object in Java?
提问by thobe
Duplicate:
复制:
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?
假设在 Intel 或 AMD 机器上的 64 位 Linux 上使用 Java 1.6 JVM,创建一个简单的对象使用多少字节的内存开销?例如,二维数组中的每一行都是一个单独的对象。如果我的阵列很大,我将使用多少 RAM?
回答by thobe
That will depend on which JVM you use.
这将取决于您使用的 JVM。
Assuming that you are not using a JVM with compressed pointers the array will consume:
假设您没有使用带有压缩指针的 JVM,数组将消耗:
- 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
- 8 个字节用于类型指针。
- 数组长度为 4 个字节。
- 数组中每个元素的 8 个字节(这些是指向实际对象的指针)。
- 总和:8+4+len*8 字节
- 对于带有压缩指针的 JVM:4+4+len*4 字节
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.
然后,您在数组中存储(引用)的实际对象将消耗内存,具体取决于它们是什么类型的对象。java.lang.Object 只包含一个指向类的指针,所以 8 个字节,如果使用压缩指针,则为 4 个字节。
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.
对于您自己的类,您可以通过查看类中的字段来计算内存使用情况。每个引用将消耗 8 个字节(压缩指针为 4 个字节)。每个long 8个字节,int 4个字节,char/short 2个字节,byte/boolean 1个字节。但是所有这些都将对齐为 4 或 8 字节的倍数的偶数总大小,具体取决于您使用的 JVM。

