What is the memory consumption of an object in Java?

前端 未结 12 2485
眼角桃花
眼角桃花 2020-11-22 03:20

Is the memory space consumed by one object with 100 attributes the same as that of 100 objects, with one attribute each?

How much memory is allocated for an object?<

12条回答
  •  没有蜡笔的小新
    2020-11-22 03:45

    Each object has a certain overhead for its associated monitor and type information, as well as the fields themselves. Beyond that, fields can be laid out pretty much however the JVM sees fit (I believe) - but as shown in another answer, at least some JVMs will pack fairly tightly. Consider a class like this:

    public class SingleByte
    {
        private byte b;
    }
    

    vs

    public class OneHundredBytes
    {
        private byte b00, b01, ..., b99;
    }
    

    On a 32-bit JVM, I'd expect 100 instances of SingleByte to take 1200 bytes (8 bytes of overhead + 4 bytes for the field due to padding/alignment). I'd expect one instance of OneHundredBytes to take 108 bytes - the overhead, and then 100 bytes, packed. It can certainly vary by JVM though - one implementation may decide not to pack the fields in OneHundredBytes, leading to it taking 408 bytes (= 8 bytes overhead + 4 * 100 aligned/padded bytes). On a 64 bit JVM the overhead may well be bigger too (not sure).

    EDIT: See the comment below; apparently HotSpot pads to 8 byte boundaries instead of 32, so each instance of SingleByte would take 16 bytes.

    Either way, the "single large object" will be at least as efficient as multiple small objects - for simple cases like this.

提交回复
热议问题