douzhanglu4591 2017-03-12 03:17
浏览 46
已采纳

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

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
  • 写回答

2条回答 默认 最新

  • duanfu5239 2017-03-12 03:38
    关注
    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:

    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条)

报告相同问题?

悬赏问题

  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程