Is an array of a boolean in Java smaller than a stand-alone variable?

advertisements

My searches on SO have failed me, so if this is a duplicate, please redirect me.

With that out of the way, my question: I learned, from experience and browsing SO that a Java boolean is stored as a 32-bit int if you declare it as a standalone value, but as an 8-bit byte if you declare it within an array. My question, here, is as follows: Which is more memory efficient? Does the meta data of the array make it bigger in memory than the alternative?

boolean oneVariable = false, oneArray[] = {false};


The "meta data" of the array includes:

  • 8 bytes (32-bit JVM) or 16 bytes (64-bit JVM) for object header
  • 4 bytes (32 bits) for the length of the array

Add on the 1 necessary byte for the boolean data and you have 13 bytes (32 bit) or 21 bytes (64 bit) at a minimum.

However, objects are allocated memory in 8-byte multiples, so even though you only need 12 or 20 bytes of overhead + 1 byte for the boolean, you'll end up using 16 or 24 bytes of memory, respectively, for your array object.

In addition to the 16/24 bytes the object itself will take up, you'll need 4 bytes (32 bit) or 8 bytes (64 bit) for the memory address of the object, totaling 20 or 32 bytes of memory, respectively, to store your boolean in an array.

The size of a standalone variable is JVM dependent. Java does not specify the size of storage, and in fact Oracle says

This data type represents one bit of information, but its "size" isn't something that's precisely defined.

Older JVMs use a 32-bit stack cell, used to hold local variables, method arguments, and expression values so a single boolean used as a variable would consume 4 bytes; making the array at least 5 times as expensive as for a single boolean. This answer may be different if, for example, the boolean is a class variable in which case it would just be a single byte added to the existing overhead. In newer JVMs a single boolean would only use 1 byte, but depending on its context and the 8-byte padding necessary to align memory addresses, could still consume up to 8 bytes of heap space. It would still be smaller than the boolean array.