boolean in Java is 8-bit large! always…!

After doing some testing and looking for some information on the Internet, I have figured out that primitive type boolean in Java is always 8-bit large, even in the array…

I can understand that for a single instance of boolean it is necessary to allocate more memory than just one bit (operating system cannot write to a single bit, but to a byte at least). It is also obvious that an object will need more memory than a primitive type. I have found an information (here) that each object has 8-byte header, plus a byte for a value, than it is rounded up to first 8-byte multiple and there is also 4 byte reference – all together, Boolean object is 20-byte large…

To reduce the amount of opcode, Sun/Oracle has not implemented a proper structure in the JVM for this. But it has been done in java.util.BitSet, which should be always used instead of array of booleans. Ok, instead of those large ones at least.

Having this information I have decided to upgrade further my Prime class. First step was to exchange array of booleans in sieve(int) method by BitSet. It allowed to use sieve of Eratosthenes for larger numbers (now it needs up to 255MB, which is acceptable), but another problem arose – there is not enough memory to store prime numbers, and there are two ideas for this:

  1. It can be found which number exceeds INT_MAX, so part of a list could be stored as integers, while the rest as longs.
  2. Because List is general purpose class it has to use objects and it is impossible to create an array of primitive types. In this case it is known that only longs will be necessary (or longs and ints). So the idea is to exchange general purpose List by a dedicated structure using array of primitive types. If I am correct it should save 8 bytes per prime number. Also it will save some time on arguments’ checking in the List.

I will try to implement it today or tomorrow.

About Jaroslaw Pawlak

I have done MSci in Computer Science at King’s College London and currently work as Software Engineer specialising in Java. I spend most of my time in front of computer improving my programming (and other) skills or just relaxing with a good game. I also train some sports but at the moment I am not a member of any club. I love cycling and volleyball, but I have also played a lot of football, tennis and trained martial arts.

Posted on June 29, 2011, in Development, Project Euler. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: