Skip to content

Commit

Permalink
reduce variable allocations in getter
Browse files Browse the repository at this point in the history
  • Loading branch information
cornelk committed Aug 28, 2022
1 parent f293cd5 commit 2ede47d
Showing 1 changed file with 2 additions and 11 deletions.
13 changes: 2 additions & 11 deletions hashmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,16 @@ func (m *HashMap[Key, Value]) Len() int {
// Get retrieves an element from the map under given hash key.
func (m *HashMap[Key, Value]) Get(key Key) (Value, bool) {
hash := m.hasher(key)
store := m.store.Load()
element := store.item(hash)

// inline HashMap.searchItem()
for element != nil {
for element := m.store.Load().item(hash); element != nil; element = element.Next() {
if element.keyHash == hash && element.key == key {
return element.Value(), true
}

if element.keyHash > hash {
return *new(Value), false
}

element = element.Next()
}
return *new(Value), false
}
Expand All @@ -84,10 +80,7 @@ func (m *HashMap[Key, Value]) GetOrInsert(key Key, value Value) (Value, bool) {
var newElement *ListElement[Key, Value]

for {
store := m.store.Load()
element := store.item(hash)

for element != nil {
for element := m.store.Load().item(hash); element != nil; element = element.Next() {
if element.keyHash == hash && element.key == key {
actual := element.Value()
return actual, true
Expand All @@ -96,8 +89,6 @@ func (m *HashMap[Key, Value]) GetOrInsert(key Key, value Value) (Value, bool) {
if element.keyHash > hash {
break
}

element = element.Next()
}

if newElement == nil { // allocate only once
Expand Down

0 comments on commit 2ede47d

Please sign in to comment.