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:
- It can be found which number exceeds INT_MAX, so part of a list could be stored as integers, while the rest as longs.
- 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.