Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::bitset<8> 4 bytes big?

It seems for std::bitset<1 to 32>, the size is set to 4 bytes. For sizes 33 to 64, it jumps straight up to 8 bytes. There can't be any overhead because std::bitset<32> is an even 4 bytes.

I can see aligning to byte length when dealing with bits, but why would a bitset need to align to word length, especially for a container most likely to be used in situations with a tight memory budget?

This is under VS2010.

like image 688
Anne Quinn Avatar asked Sep 22 '11 07:09

Anne Quinn


People also ask

How much memory does Bitset use?

As expected, the BitSet with the same number of bits consumes around 1 KB, which is far less than the boolean[].

What is the size of Bitset?

The default size of the bit set is 64-bit space. If the bit is set at index larger than the current BitSet size, it increases its bit space in the multiplication of 64*n, where n starts from 1, 2, 3, so on.

Is Bitset faster than vector bool?

As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector. We can access each bit of bitset individually with help of array indexing operator [] that is bs[3] shows bit at index 3 of bitset bs just like a simple array.

What data type is Bitset?

Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.


1 Answers

The most likely explanation is that bitset is using a whole number of machine words to store the array.

This is probably done for memory bandwidth reasons: it is typically relatively cheap to read/write a word that's aligned at a word boundary. On the other hand, reading (and especially writing!) an arbitrarily-aligned byte can be expensive on some architectures.

Since we're talking about a fixed-sized penalty of a few bytes per bitset, this sounds like a reasonable tradeoff for a general-purpose library.

like image 144
NPE Avatar answered Oct 03 '22 22:10

NPE