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

huangapple go评论97阅读模式
英文:

Why don't they use ints to define constants instead of using bit shift operators?

问题

go源代码中,常量bucketCnt的值是8。为什么要通过右移3次来定义它,而不是直接定义为8呢?

我知道1 << x表示2^x

但是,我的问题是...

是这样的:

// 一个桶可以容纳的键/值对的最大数量。
bucketCntBits = 3
bucketCnt     = 1 << bucketCntBits

比这样的好吗:

// 一个桶可以容纳的键/值对的最大数量。
bucketCnt     = 8
英文:

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 &lt;&lt; x implies 2^x.

But, my question is...

Is

// Maximum number of key/value pairs a bucket can hold.
bucketCntBits = 3
bucketCnt     = 1 &lt;&lt; bucketCntBits

better than

// Maximum number of key/value pairs a bucket can hold.
bucketCnt     = 8

答案1

得分: 5

const (
    // 桶(bucket)可以容纳的键值对的最大数量。
    bucketCntBits = 3
    bucketCnt     = 1 << bucketCntBits
)

桶(bucket)可以容纳的键值对数量取决于使用的位数(bucketCntBits = 3)。这意味着桶的数量(bucketCnt)为1 << bucketCntBits,即8。如果我们将位数更改为4(bucketCntBits = 4)或2(bucketCntBits = 2),那么bucketCnt仍然为1 << bucketCntBits,即16或4。

// Map只是一个哈希表。数据被组织成一个桶(bucket)的数组。每个桶最多包含8个键值对。哈希的低位用于选择一个桶。每个桶包含一些哈希的高位,以区分单个桶中的条目。

"哈希的低位用于选择一个桶。"

参考资料:

src/runtime/hashmap.go

Go maps in action

GopherCon 2016: Keith Randall - Inside the Map Implementation

Macro View of Map Internals In Go (2013)

英文:

> 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 &lt;&lt; bucketCntBits or 8. If we change the number of bits to 4 (bucketCntBits = 4) or 2 (bucketCntBits = 2) then bucketCnt is still 1 &lt;&lt; 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:

src/runtime/hashmap.go

Go maps in action

GopherCon 2016: Keith Randall - Inside the Map Implementation

Macro View of Map Internals In Go (2013)

答案2

得分: 1

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

英文:

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.

huangapple
  • 本文由 发表于 2017年3月12日 11:17:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/42743322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定