Search code examples
javabit-manipulationbitset

Why would you use a BitSet in java as opposed to an array of booleans (in Java)?


Other than the difference in methods available, why would someone use a BitSet as opposed to an array of booleans? Is performance better for some operations?


Solution

  • You would do it to save space: a boolean occupies a whole byte, so an array of N booleans would occupy eight times the space of a BitSet with the equivalent number of entries.

    Execution speed is another closely related concern: you can produce a union or an intersection of several BitSet objects faster, because these operations can be performed by CPU as bitwise ANDs and ORs on 32 bits at a time.