I'm trying to get a general idea of the memory cost difference between an Integer array and int array. While there seems to be a lot of information out there about the differences between a primitive int and Integer object, I'm still a little confused as to how to calculate the memory costs of an int[] and Integer[] array (overhead costs, padding, etc).
Any help would be appreciated. Thanks!
-
4stackoverflow.com/questions/8419860/…Héctor Valls– Héctor Valls2014年08月21日 10:22:43 +00:00Commented Aug 21, 2014 at 10:22
-
@bigdestroyer Thank you, but I'm asking about arrays in this case.Fitzy123– Fitzy1232014年08月21日 10:24:15 +00:00Commented Aug 21, 2014 at 10:24
-
possible duplicate of In Java, what is the best way to determine the size of an object?JaskeyLam– JaskeyLam2014年08月21日 10:27:51 +00:00Commented Aug 21, 2014 at 10:27
-
@ThomasJungblut: Is it? Presumably an array of primitives involves almost no overhead, an array of references imposes the storage for all the references as well as the referred-to objects.Oliver Charlesworth– Oliver Charlesworth2014年08月21日 10:38:23 +00:00Commented Aug 21, 2014 at 10:38
2 Answers 2
In addition to storing the length of the array, an array of int
s needs space for N 4-byte elements, while an array of Integer
s needs space for N references, whose size is platform-dependent; commonly, that would be 4 bytes on 32-bit platforms or 8 bytes on 64-bit platforms.
As far as int[]
goes, there is no additional memory required to store data. Integer[]
, on the other hand, needs objects of type Integer
, which could be all distinct or shared (e.g. through interning of small numbers implemented by the Java platform itself). Therefore, Integer[]
requires up to N additional objects, each one containing a 4-byte int
.
Assuming that all Integer
s in an Integer[]
array are distinct objects, the array and its content will take two to three times the space of an int[]
array. On the other hand, if all objects are shared, and the memory costs of shared objects are accounted for, there may be no additional overhead at all (on 32-bit platforms) or the there would be a 2x overhead on 64-bit platforms.
2 Comments
Here is a comparison on jdk6u26 of the size of an array of 1024 Integer
s as opposed to 1024 int
s. Note that in the case of anInteger[]
array containing low number Integer
s, these can be shared with other uses of these Integer
s in the JVM by the auto-box cache.