为什么std :: bitset< 8>4个字节大吗? [英] Why is std::bitset<8> 4 bytes big?

查看:81
本文介绍了为什么std :: bitset< 8>4个字节大吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎对于std :: bitset< 1到32>,大小设置为4个字节.对于33到64的大小,它直接跳到8个字节.不会有任何开销,因为std :: bitset< 32>是偶数4个字节.

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?

这是在VS2010下进行的.

This is under VS2010.

推荐答案

我假定通过获取32位值然后隔离相关位来完成对该位集的索引,因为这在处理器指令方面是最快的(有效较小的值在x86上速度较慢).为此所需的两个索引也可以很快地计算出来:

I assume that indexing into the bitset is done by grabbing a 32-bit value and then isolating the relevant bit because this is fastest in terms of processor instructions (working with smaller-sized values is slower on x86). The two indexes needed for this can also be calculated very quickly:

int wordIndex = (index & 0xfffffff8) >> 3;
int bitIndex = index & 0x7;

然后您可以执行此操作,这也非常快:

And then you can do this, which is also very fast:

int word = m_pStorage[wordIndex];
bool bit = ((word & (1 << bitIndex)) >> bitIndex) == 1;

此外,每个位集最多浪费3个字节也不完全是内存问题恕我直言.考虑到位集已经是存储此类信息的最有效的数据结构,因此您必须将浪费作为总结构大小的百分比进行评估.

Also, a maximum waste of 3 bytes per bitset is not exactly a memory concern IMHO. Consider that a bitset is already the most efficient data structure to store this type of information, so you would have to evaluate the waste as a percentage of the total structure size.

对于1025位,此方法将占用132个字节而不是129个字节,从而占用2.3%的开销(并且随着位集站点的增加而减少).考虑到可能的性能优势,这听起来很合理.

For 1025 bits this approach uses up 132 bytes instead of 129, for 2.3% overhead (and this goes down as the bitset site goes up). Sounds reasonable considering the likely performance benefits.

这篇关于为什么std :: bitset&lt; 8&gt;4个字节大吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆