【问题标题】:What's the difference between using & vs MOD operators in calculating indexes (Hash Table implementation)?在计算索引(哈希表实现)中使用 & vs MOD 运算符有什么区别?
【发布时间】:2019-04-17 22:26:01
【问题描述】:

对于一般的哈希表实现:

  • 计算密钥的哈希值, hash(key)=hashcode

  • 将哈希码映射到表/数组。 hashcode % array_length = index

  • 一旦我们得到索引,我们就在该索引处的链表中添加一个节点(键、值、更新下一个指针)。

那么,问题是,两者有什么区别:

def _get_index(self, key):

   # compute the hashcode
   hash_code = hash(key)
   array_index = hash_code & 15  # FIXME : why?
   return array_index

 array_index = hash_code % 15

例如: 输入:

hm =MyHashMap()
hm.put("1", "sachin")
hm.put("2", "sehwag")
hm.put("3", "ganguly")
print(hm.get("1"))
print(hm.get("2"))
print(hm.get("3"))

输出:

sachin
sehwag
ganguly

'&' 运算符而不是 '%' 这对我来说没有意义吗?因为它在计算索引时并不总是作为 % 运算符工作,但是,我见过开发人员在 Hashtable 的某些实现中使用 &

有什么建议吗?

【问题讨论】:

    标签: python python-3.x hash hashmap hashcode


    【解决方案1】:
    array_index = hash_code & 15
    

    等价于(正值):

    array_index = hash_code % 16
    

    它仅适用于数字的所有有效位均为 1 的情况(即数字的形式为 2**n - 1)。

    两者都删除了数字位的最高部分。

    位掩码比除法快得多。因此,在可能的情况下使用它来加快计算速度。每次看到:

    b = a % modulo
    

    a > 0modulo 是 2 的幂 (modulo == 2**n),你可以这样写:

    b = a & (modulo-1)
    

    相反。如果模不是 2 的幂,则不能那样做(编译语言优化器通常用更快的位掩码/移位操作代替 2 的幂或除/乘)

    即使位掩码确实比汇编语言中的除法/模数快得多,python 也被解释并且速度优化并不是很明显。无论如何,如果意图是屏蔽位,& 运算符更有意义。

    【讨论】:

    • 不过,对于 Python int 对象,x % 16x & 15 之间的速度差异很小。
    • 可能,但是为什么让它变慢呢?
    • 我在 & 稍慢的地方进行了测试。处理 Python 对象的开销似乎压倒了底层算法中可能存在的任何差异。
    • 第 1 课:避免过早优化 :) 如果您在汇编中编写例程代码,掩码会更快。否则,编译器会处理这个问题。 Python 会随心所欲。
    猜你喜欢
    • 2011-05-29
    • 2023-03-04
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2012-06-03
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多