在go source code中,常数bucketCnt
为8.为什么定义为右移3次而不是仅将其定义为8。
我了解1 << x
暗示2^x
。
但是,我的问题是......
时
// Maximum number of key/value pairs a bucket can hold.
bucketCntBits = 3
bucketCnt = 1 << bucketCntBits
优于
// Maximum number of key/value pairs a bucket can hold.
bucketCnt = 8
答案 0 :(得分:5)
const ( // Maximum number of key/value pairs a bucket can hold. bucketCntBits = 3 bucketCnt = 1 << bucketCntBits )
存储桶可以容纳的键/值对的数量取决于使用的位数(bucketCntBits = 3
)。这转换为bucketCnt
或8的桶数(1 << bucketCntBits
)。如果我们将位数更改为4(bucketCntBits = 4
)或2(bucketCntBits
= 2),那么bucketCnt
仍为1 << bucketCntBits
或16或4.
// A map is just a hash table. The data is arranged // into an array of buckets. Each bucket contains up to // 8 key/value pairs. The low-order bits of the hash are // used to select a bucket. Each bucket contains a few // high-order bits of each hash to distinguish the entries // within a single bucket.
“散列的低位用于选择存储桶。”
参考文献:
GopherCon 2016: Keith Randall - Inside the Map Implementation
答案 1 :(得分:1)
使用位移运算符集bucketCnt
根据bucketCntBits
中的值进行定义,因此如果更改bucketCntBits
,bucketCnt
将相应更改。此外,它更清楚地表达bucketCntBits
与bucketCnt
的关系。