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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度