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 boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null.
Boolean takes up 16 bytes of memory.
Unlike C++, a numerical value cannot be assigned to a boolean variable in Java – only true or false can be used.
The Array is an actual Object that comes with a memory penalty (I believe 12 bytes) So the primitive boolean is smaller.
The "meta data" of the array includes:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With