Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much space does an array occupy?

Tags:

java

arrays

If I create 10 integers and an integer array of 10, will there be any difference in total space occupied?

I have to create a boolean array of millions of records, so I want to understand how much space will be taken by array itself.

like image 990
banjara Avatar asked Jul 13 '12 08:07

banjara


People also ask

How much space does array take?

That is typically 5 words or 20 bytes per element of the array ... unless some Integer objects appear in multiple places in the array.

What is a size of an array?

The physical size of the array is the total number of slots that are available. For example, if array A is created by. int A[15]; then A has physical size 15. The logical size of an array is the total number of occupied slots.

How much space does an array take in C++?

Arrays take up the element size times the number of elements. Pointers take up the space needed to hold an address, which is 4 bytes on a 32-bit machine and 8 bytes on a 64-bit machine.

How much can an array store?

The theoretical maximum Java array size is 2,147,483,647 elements.


1 Answers

An array of integers is represented as block of memory to hold the integers, and an object header. The object header typically takes 3 32bit words for a 32 bit JVM, but this is platform dependent. (The header contains some flag bits, a reference to a class descriptor, space for primitive lock information, and the length of the actual array. Plus padding.)

So an array of 10 ints probably takes in the region of 13 * 4 bytes.

In the case on an Integer[], each Integer object has a 2 word header and a 1 word field containing the actual value. And you also need to add in padding, and 1 word (or 1 to 2 words on a 64-bit JVM) for the reference. That is typically 5 words or 20 bytes per element of the array ... unless some Integer objects appear in multiple places in the array.


Notes:

  1. The number of words actually used for a reference on a 64 bit JVM depends on whether "compressed oops" are used.
  2. On some JVMs, heap nodes are allocated in multiples of 16 bytes ... which inflates space usage (e.g. the padding mentioned above).
  3. If you take the identity hashcode of an object and it survives the next garbage collection, its size gets inflated by at least 4 bytes to cache the hashcode value.
  4. These numbers are all version and vendor specific, in addition to the sources of variability enumerated above.
like image 185
Stephen C Avatar answered Sep 27 '22 21:09

Stephen C