Reputation: 4556
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.
Upvotes: 1
Views: 3386
Reputation: 533920
On most JVMs; an array or object has a 12-16 byte overhead. An int
use 4 bytes and a boolean
uses 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 an int[]
can be smaller than a BitSet
but as the size grows, BitSet will be the smallest.
If the data structure is smaller than your cache the fastest is int[]
then boolean[]
then BitSet
This is because there is non-trival overhead in breaking int
into byte
or 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.
Upvotes: 3
Reputation: 38152
Consider to replace bit flags with enums. Then you can use e.g. EnumSet instead of Bitset.
Upvotes: 0
Reputation: 10789
Actually, it is JVM dependent. For example Sun JVM converts boolean
type to int
. That mean even boolean variable uses 32 bit. But jvm optimize boolean arrays, and reserve 8 bit per boolean array cell.
Upvotes: 1
Reputation: 13882
Descending order in memory usage
int[n] > Bitset(n) > boolean[n]
However, in accessing the indexes, there should not be any difference.
Upvotes: 0
Reputation: 26930
Java store boolean
as int
internally. So int[]
and boolean[]
is exactly the same.
BitSet
use less memory. Faster or not depends on your usage pattern.
Upvotes: 0