Wsm2110 / Faster.Map

Faster.Map is a high-performance, thread-safe key-value store designed to outperform the standard Dictionary and ConcurrentDictionary
MIT License
75 stars 7 forks source link

GetOrAddValueRef #26

Closed artelk closed 1 year ago

artelk commented 1 year ago

It would be good to expose a method

public ref TValue GetOrAddValueRef(TKey key)

(like in DictionarySlim). That would help in case the TValue is a big struct and also to avoid double-lookups in quite common scenario like:

if (map.Get(key, out var oldValue)) // 1st
  map.Update(key, CalculateNewValue(oldValue)); //2nd
else
  map.Emplace(key, default); //2nd

vs.

ref var value = ref map.GetOrAddValueRef(key);
value = CalculateNewValue(value);
Wsm2110 commented 1 year ago

Interesting. Ill add some api changes in the next release

Wsm2110 commented 1 year ago

Added 'EmplaceOrUpdate' In cases where you don't know if the keyValuePair exists, this will result in 1 lookup.

artelk commented 1 year ago

Thank you. But it seems it doesn't really help for the scenario above. The CalculateNewValue method needs the previous value.

if (someCountersMap.Get(key, out var oldValue))
  someCountersMap.Update(key, oldValue+1);
else
  someCountersMap.Emplace(key, 1);
Wsm2110 commented 1 year ago

I'm just wondering why you can't replace

if (someCountersMap.Get(key, out var oldValue)) someCountersMap.Update(key, oldValue+1); else someCountersMap.Emplace(key, 1);

With

SomeCountersMap.EmplaceOrUpdate(key, value)

Pretty much seems to do exactly what you suggested, or im i missing something?

Op ma 24 apr. 2023 11:53 schreef Artem Elkin @.***>:

Thank you. But it seems it doesn't really help for the scenario above. The CalculateNewValue method needs the previous value.

if (someCountersMap.Get(key, out var oldValue)) someCountersMap.Update(key, oldValue+1);else someCountersMap.Emplace(key, 1);

— Reply to this email directly, view it on GitHub https://github.com/Wsm2110/Faster.Map/issues/26#issuecomment-1519782605, or unsubscribe https://github.com/notifications/unsubscribe-auth/AD4KISMBHK46NBHH267YVHLXCZER7ANCNFSM6AAAAAAXC2GIKI . You are receiving this because you modified the open/close state.Message ID: @.***>

artelk commented 1 year ago

How can you increment the existing counter value for some key in the map using EmplaceOrUpdate(key, value)? With GetOrAddValueRef it would be just:

someCountersMap.GetOrAddValueRef(key)++; // one lookup only
Wsm2110 commented 1 year ago

Ok, Gotcha.

Op ma 24 apr. 2023 12:07 schreef Artem Elkin @.***>:

How can you increment the existing counter value for some key in the map using EmplaceOrUpdate(key, value)?

— Reply to this email directly, view it on GitHub https://github.com/Wsm2110/Faster.Map/issues/26#issuecomment-1519834455, or unsubscribe https://github.com/notifications/unsubscribe-auth/AD4KISPJ37JGO43HS255ZDDXCZGHNANCNFSM6AAAAAAXC2GIKI . You are receiving this because you modified the open/close state.Message ID: @.***>