1

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!

Fitzy123
  • 141
  • 1
  • 1
  • 6
  • 4
    http://stackoverflow.com/questions/8419860/integer-vs-int-with-regard-to-memory – Héctor Aug 21 '14 at 10:22
  • @bigdestroyer Thank you, but I'm asking about arrays in this case. – Fitzy123 Aug 21 '14 at 10:24
  • possible duplicate of [In Java, what is the best way to determine the size of an object?](http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object) – JaskeyLam Aug 21 '14 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 Aug 21 '14 at 10:38

2 Answers2

8

In addition to storing the length of the array, an array of ints needs space for N 4-byte elements, while an array of Integers 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 Integers 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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Here is a comparison on jdk6u26 of the size of an array of 1024 Integers as opposed to 1024 ints. Note that in the case of anInteger[] array containing low number Integers, these can be shared with other uses of these Integers in the JVM by the auto-box cache.

MilesHampson
  • 2,069
  • 24
  • 43