In the go source code, the constant bucketCnt
is 8. Why is defined in terms of right-shifting 3 times instead of just defining it as 8. I understand that 1 << x
implies 2^x
.
But, my question is...
Is
// Maximum number of key/value pairs a bucket can hold.
bucketCntBits = 3
bucketCnt = 1 << bucketCntBits
better than
// Maximum number of key/value pairs a bucket can hold.
bucketCnt = 8
const ( // Maximum number of key/value pairs a bucket can hold. bucketCntBits = 3 bucketCnt = 1 << bucketCntBits )
The number of key/value pairs a bucket can hold depends on the number of bits used (bucketCntBits = 3
). That translates to a bucket count (bucketCnt
) of 1 << bucketCntBits
or 8. If we change the number of bits to 4 (bucketCntBits = 4
) or 2 (bucketCntBits
= 2) then bucketCnt
is still 1 << bucketCntBits
or 16 or 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.
"The low-order bits of the hash are used to select a bucket."
References:
GopherCon 2016: Keith Randall - Inside the Map Implementation
Using bit shift operators sets bucketCnt
to be defined according to the value in bucketCntBits
, so if bucketCntBits
is changed, bucketCnt
will change accordingly. Also, it more clearly expresses how bucketCntBits
is related to bucketCnt
.