In Java, what is faster and less in memory: int[n] or boolean[n] or maybe Bitset(n) ?
The question is applicable for arrays of small (n is up to 1000), medium (n is between 1000 and 100000) and huge (n is greater than 100000) sizes. Thank you.
I want to achieve flags (1/0) storage.
On most JVMs; an array or object has a 12-16 byte overhead. An
intuse 4 bytes and abooleanuses a byte (it doesn’t have to but it does with OpenJDK/HotSpot) BitSet uses two objects and more memory for small sets, but only one bit per have. So for small collections anint[]can be smaller than aBitSetbut as the size grows, BitSet will be the smallest.If the data structure is smaller than your cache the fastest is
int[]thenboolean[]thenBitSetThis is because there is non-trival overhead in breakingintintobyteor a bit.However once your cache size becomes important, it can be that the overhead of BitSet fades compared to the overhead of using a slower cache or main memory.
In short: if in doubt use BitSet as this is clearer as to your intent and its likely to be faster.