HashMap Entry stability

Hi Rustaceans,

I'm using a HashMap for counting items over a data stream, i.e., every time I see an element, I look up the element in the HashMap and increment the value and after a certain time period I decrement the value with the same procedure. All of this is happening in a single thread.

Currently I'm hashing twice, once for incrementing and once for decrementing counts for elements. As I am using the Entry API anyways, I was wondering, whether I could store an Entry of a counted element and reuse the Entry for decrementing after the timeout.

This would half the requirements in terms of CPU as I do not have to hash each element twice. On the other hand, it requires the Entry to remain stable even if the HashMap is reorganized or the Entry is incremented twice within the time window.

Before reorganizing my code: is this even possible or do you see fundamental problems with this approach?

Kind regards

If you want to memoize a hash, you could use hashbrown’s HashMap API, and in particular raw entries (check the linked docs for usage examples).

1 Like

The most obvious thing here is that HashMap::entry takes &mut self, i.e. you can't do anything at all with the hashmap while the entry exists other then manipulate the entry itself.


Thank you for pointing that out, that was the first issue I ran into when fiddling with the code.

That looks interesting. Is hashbrown comaparable to the standard HashMap in terms of performance? Looking at the docs they both seem to implement Google's SwissTable.

1 Like

The standard library HashMap actually uses hashbrown internally.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.