为什么他们不使用int来定义常量而不是使用位移运算符?

时间:2017-03-12 03:17:54

标签: go

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

2 个答案:

答案 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.

“散列的低位用于选择存储桶。”

参考文献:

src/runtime/hashmap.go

Go maps in action

GopherCon 2016: Keith Randall - Inside the Map Implementation

Macro View of Map Internals In Go (2013)

答案 1 :(得分:1)

使用位移运算符集bucketCnt根据bucketCntBits中的值进行定义,因此如果更改bucketCntBitsbucketCnt将相应更改。此外,它更清楚地表达bucketCntBitsbucketCnt的关系。