C++ provides the bitset
to store bits. As per the reference, the class emulates an array of bool
elements, but optimized for space allocation. In which cases one should be preferred to the other?
As shown above, the boolean [] has a better throughput on smaller sizes. When the number of bits increases, the BitSet outperforms the boolean [] in terms of throughput. To be more specific, after 100,000 bits, the BitSet shows superior performance.
Bitsets (stored in memory as a continuous sequence of bytes) are only faster if bit operations can be performed in parallel on many bits at a time. For example, if you implement your own bitset in C using an array of ints (four bytes each) and perform operations on all bits simultaneously, the resulting code could be up to 32 times faster.
Avoid the typical pitfalls and headaches that are often associated with coding in C++. It depends. Bitsets (stored in memory as a continuous sequence of bytes) are only faster if bit operations can be performed in parallel on many bits at a time.
C++ bitset and its application Difficulty Level : Easy Last Updated : 04 Sep, 2018 A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs [N] and vector bs (N).
The right thing is to take measurements.
Nonetheless, as I recall, docs about bitsets always said that a bit set is not guaranteed to be real bits, it's just a recommendation for the compiler and a convenient syntax for bits manipulation.
On embedded systems compilers, many use real bitsets because working with bits is a real necessity in such a kind of programs.
As for speed, the opposite is more reasonable - working with arrays is simpler by means of indexing. Working with bits requires more math, to access the correct word and then access the correct bit.
I had the same question so I made a benchmark for searching a sequence. Because bitset doesn't have iterators I had to make a "std::search" alternative for bitset.
c-lang 8.0 results:
64 bits => bitset 1.2 times slower than array
128 bits => bitset 1.4 times slower than array
1024 bits => bitset 1.5 times slower than array
4096 bits => bitset 1.5 times slower than array
gcc 9.1 results:
64 bits => bitset 1.6 times faster than array
128 bits => bitset 1.5 times faster than array
1024 bits => bitset 1.4 times faster than array
4096 bits => bitset 1.4 times faster than array
Total unexpected results.
The benchmark can be run here http://quick-bench.com/-er6qDrx0dPmJ0rGnJ9t3EpLoMM
Update 2020-09
Using Clang 10.0 and GCC 10.1, in both cases the array of bools is faster than bitset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With