英文:
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 << 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
答案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个键值对。哈希的低位用于选择一个桶。每个桶包含一些哈希的高位,以区分单个桶中的条目。
"哈希的低位用于选择一个桶。"
参考资料:
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 << 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
答案2
得分: 1
使用位移运算符将bucketCnt设置为根据bucketCntBits中的值定义,因此如果更改bucketCntBits,bucketCnt将相应更改。此外,它更清楚地表达了bucketCntBits与bucketCnt的关系。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论