In Java, the character data type, char
, is represented with 2 bytes. The array of n
characters, char[]
, is represented with 2n+24
bytes.
In general, there is an overhead of 24
bytes for storing an array of n
objects (at least if the objects are of primitive type).
Why do we need these additional 24 bytes? How are they used?
EDIT (July 2nd 2015). It was brought to my attention in a comment that an answer to this question is offered here on the programmers StackExchange.
In general, there is an overhead of 24 bytes for storing an array of n objects (at least if the objects are of primitive type).
The memory allocation for an array includes the header object of 12 bytes plus the number of elements multiplied by the size of the data type that will be stored and padding as needed for the memory block to be a multiple of 8 bytes.
Elements in an array are stored literally right next to each other in memory (so we can have index for fast lookups). But nodes in linked lists have no such restriction (which is why there's no index lookup for linked lists) — each and every item can be stored anywhere on the memory block.
It is the object header, it includes information about the object itself (locked bits, marked bits for the GC), a pointer to its class object and the length.
In addition to object headers and length prefix all java objects also have to be aligned, usually to pointer sizes, possibly multiples thereof (there's an option to tune object alignment).
The need for alignment means there has to be padding end of each object - and thus the array - if the subsequent object wouldn't align properly. That concern will be most prominent with byte[]
arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With