Java中对象的内存开销是多少? [英] What is the memory overhead of an object in Java?
问题描述
假设在Intel或AMD机器上的64位Linux上使用Java 1.6 JVM,创建一个简单的对象会使用多少内存开销(以字节为单位)?例如,二维数组中的每一行都是一个单独的对象。如果我的数组很大,我将使用多少RAM?
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?
推荐答案
这将取决于您使用的JVM。
That will depend on which JVM you use.
假设您没有使用带有压缩指针的JVM,数组将消耗:
Assuming that you are not using a JVM with compressed pointers the array will consume:
- 8字节用于类型指针。
- 数组长度为4个字节。
- 数组中每个元素的8个字节(这些是指向实际对象)。
- 总和:8 + 4 + len * 8字节
- 对于带压缩指针的JVM:4 + 4 + len * 4个字节
- 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
然后,您在数组中存储(引用)的实际对象将消耗内存,具体取决于它们是什么类型的对象。 java.lang.Object只包含一个指向该类的指针,因此如果使用压缩指针则为8个字节或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.
对于您自己的类,您可以计算内存使用情况通过查看班级中的字段。
每个引用将消耗8个字节(压缩指针为4个字节)。每个长8个字节,int 4个字节,char / short 2个字节,byte / boolean 1个字节。但是所有这些都将与一个4或8个字节的倍数的偶数总大小对齐,具体取决于您使用的JVM。
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.
这篇关于Java中对象的内存开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!