Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for the overhead in memory usage for arrays in Java?

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.

like image 874
blazs Avatar asked Jul 02 '15 10:07

blazs


People also ask

What is the overhead of an array?

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).

How much memory does an array use in Java?

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.

How does array use memory?

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.


2 Answers

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.

like image 134
loonytune Avatar answered Oct 10 '22 01:10

loonytune


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.

like image 29
the8472 Avatar answered Oct 10 '22 02:10

the8472