The theoretical size of the array would be :
numberOfElementsInTheArray * 4 bytes
12 bytes of headers (int[]
is an Object). Actually the size of headers depends on the flags you used and on the JVM version you are running this
4 bytes to keep the length
of the array
padding.
For example: (I am going to use JOL for this):
int [] x = new int[10];
for(int i=0;i<10;++i){
x[i] = 9999;
}
System.out.println(GraphLayout.parseInstance((Object)x).toPrintable());
will output:
[I@7a81197dd object externals:
ADDRESS SIZE TYPE PATH VALUE
70fe45268 56 [I [9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999]
So it has 56 bytes
:
- 40 for the values themselves (10 ints * 4 bytes)
- 12 for headers
- 4 for length
- 0 for padding
If you change this array to Integer
, things change dramatically. Integer
is an Object so you will store a reference inside the array (which could be 4
or 8
bytes, depending on UseCompressedOops
flag), plus each of the Integer
instances will require 2 headers (each Integer
is an Object).
Integer[] y = new Integer[10];
for(int i=0;i<10;++i){
y[i] = 9999;
}
System.out.println(GraphLayout.parseInstance((Object)y).toFootprint());
which will show:
[Ljava.lang.Integer;@369f73a2d footprint:
COUNT AVG SUM DESCRIPTION
1 56 56 [Ljava.lang.Integer;
10 16 160 java.lang.Integer
11 216 (total)
A total of 216 bytes
:
- 4 bytes for each reference (I have
UseCompressedOop
turned on), 40 bytes total
- 12 bytes headers of the array
- 4 bytes length of the array
- 0 bytes padding
Each reference from that array points to an Integer
, each of those Objects will have 16 bytes
:
- 4 bytes for the inner
int
they hold
- 12 bytes headers
- 0 bytes padding