Page 1 of 1

How much memory does Boolean take

Posted: Wed Mar 28, 2012 11:01 am
by matejdro
How much memory does java Boolean take?

Re: How much memory does Boolean take

Posted: Wed Mar 28, 2012 11:13 am
by gloomyandy
1 byte in most cases, but you may want to provide some more details as to what it is you are doing and why you need to know the size for a more complete answer...

Andy

Re: How much memory does Boolean take

Posted: Wed Mar 28, 2012 11:19 am
by matejdro
Well, I'm making Big array of my own class, and I want that class to be as small as possible, so I can fit as big array as possible into NXT limited memory.

Re: How much memory does Boolean take

Posted: Wed Mar 28, 2012 11:49 am
by gloomyandy
Oh and do you mean Boolean or boolean? boolean is a primitive type, Boolean is an object that contains a boolean... Assuming you mean boolean then my previous answer is correct, if you mean Boolean then once you have read the following you can probably work it for yourself...

In which case you may need to understand a lot more than just the size of a boolean... Firstly an instance of a class has a fixed amount of overhead in the form of a header for a normal (none array class) this header is 4 bytes in size. Then there is is the issue of alignment, objects in memory are always stored aligned on 32 bit boundaries, fields within an object are packed and so are not aligned, though you will get slightly faster access to things like ints and longs if you can arrange the order of your fields such that they are correctly aligned (the linker generates faster byte code operations for correctly aligned fields). This object alignment means that an object contain a single boolean will not occupy 5 bytes (1 byte for the boolean plus the 4 byte header), but will actually occupy 8 bytes (with three unused padding bytes).

Since you plan to have an array of these objects, remember that in Java and array of objects is actually an array of references to an object so if say you have a class that has a single data field that is a boolean and you want to have 100 of these stored in an array then the actual memory used will be....
8 bytes for each object * 100 = 800 bytes
4 bytes per reference * 100 + array object header = 408 bytes

Andy

Re: How much memory does Boolean take

Posted: Wed Mar 28, 2012 12:01 pm
by matthias
When Memory is the limiting factor, you could put more than one(8) booleans into a byte - but that needs some packing and unpacking, when you want to access it.

Re: How much memory does Boolean take

Posted: Wed Mar 28, 2012 12:08 pm
by skoehler
Take a look at java.util.BitSet.
It uses a int array internally and stores 32 bits per int.

Re: How much memory does Boolean take

Posted: Wed Mar 28, 2012 12:36 pm
by matejdro
Wow that bitset looks promising. Thanks.