LSD Gaga
LSD Gaga

Reputation: 11

Does an array containing 1 element take up same amount of memory as that 1 element?

Let's say there's a Cat object, and whenever a new Cat is created, the same amount of memory is allocated to it every time. Now look at the following code:

Cat aSingleCat = new Cat(); // X amount of memory is allocated to 'aSingleCat'

Cat[] oneElmCatArray = new Cat[1];
oneElmCatArray[0] = new Cat(); // Same amount of memory is allocated to the only index of this 1-element array

So what does this mean? Does oneElmCatArray take up the same amount of memory as aSingleCat, or does it take up more because of some behind-the-scenes Java Array shenanigans?

Upvotes: 1

Views: 233

Answers (2)

KidCoder
KidCoder

Reputation: 363

Really interesting question! Yes - there is > 24 bytes of Array overhead associated with Arrays in Java.

This is because Arrays are simply objects in Java. So the header, variables etc. add to the space. Furthermore, the objects need to be padded to 8 bytes in Java. Since your element would need to be padded and the array, too, it will take more memory!

Aside! Object Padding: Why do Java objects have to be a multiple of 8?

EDIT: Found a really great resource @ SWE StackExchange Why the overhead when allocating objects/arrays in Java?

The answer goes more in-depth on what I wrote. You should definitely check it out if you are interested in learning more. :)

Upvotes: 0

Stephen C
Stephen C

Reputation: 719739

Does oneElmCatArray take up the same amount of memory as aSingleCat, or does it take up more because of some behind-the-scenes Java array shenanigans?

The answer is: it depends.

First of all, it is important1 that you understand what a Cat[] actually contains.

  • It does not contain Cat objects.
  • It actually contains either references to Cat objects, OR null references.

In each case, a reference will occupy either 4 or 8 bytes depending on the JVM platform and (in some cases) the command line options.

So, does a Cat occupy more memory than a Cat[1]? The answer will actually depend on:

  • The size of a reference (see above)
  • The number and type of the instance fields of the Cat class ... which is unspecified in your question.

When doing the actual calculations, you need to include the sizes of the respective native object / array headers (8 and 12 bytes respectively). Also, take account of the fact that JVM heap node sizes are a multiple of 8 bytes. (But these things are in theory implementation dependent.)

Finally, as @Louis Wasserman points out, the answer also depends on your "accounting" rules. When Cat[] contains a reference to a Cat, do you count the Cat as part of the array or not?


1 - If you don't understand this, you are going to end up with an incorrect mental model of arrays and how they work. That is likely to lead to bugs in your code.

Upvotes: 1

Related Questions