Skip to content

Commit

Permalink
[Stdlib] Speedup Dict (changing modulus to bitshifting)
Browse files Browse the repository at this point in the history
Signed-off-by: rd4com <144297616+rd4com@users.noreply.github.com>
  • Loading branch information
rd4com committed Jun 17, 2024
1 parent 87266e7 commit 9d29c48
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions stdlib/src/collections/dict.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ from builtin.value import StringableCollectionElement

from .optional import Optional


trait KeyElement(CollectionElement, Hashable, EqualityComparable):
"""A trait composition for types which implement all requirements of
dictionary keys. Dict keys must minimally be Movable, Hashable,
Expand Down Expand Up @@ -888,10 +887,11 @@ struct Dict[K: KeyElement, V: CollectionElement](
fn _next_index_slot(self, inout slot: Int, inout perturb: UInt64):
alias PERTURB_SHIFT = 5
perturb >>= PERTURB_SHIFT
slot = ((5 * slot) + int(perturb + 1)) % self._reserved()
slot = ((5*slot)+int(perturb+1)) & (self._reserved()-1)


fn _find_empty_index(self, hash: Int) -> Int:
var slot = hash % self._reserved()
var slot = hash & (self._reserved()-1)
var perturb = bitcast[DType.uint64](Int64(hash))
while True:
var index = self._get_index(slot)
Expand All @@ -901,7 +901,7 @@ struct Dict[K: KeyElement, V: CollectionElement](

fn _find_index(self, hash: Int, key: K) -> (Bool, Int, Int):
# Return (found, slot, index)
var slot = hash % self._reserved()
var slot = hash & (self._reserved()-1)
var perturb = bitcast[DType.uint64](Int64(hash))
while True:
var index = self._get_index(slot)
Expand Down Expand Up @@ -1151,3 +1151,4 @@ struct OwnedKwargsDict[V: CollectionElement](Sized, CollectionElement):
@always_inline("nodebug")
fn _insert(inout self, key: StringLiteral, owned value: V):
self._insert(String(key), value^)

0 comments on commit 9d29c48

Please sign in to comment.