- Rust Standard Library Cookbook
- Jan Nils Ferner Daniel Durante
- 237字
- 2021-08-27 19:45:13
There's more...
Internally, you can imagine the HashMap as being implemented as two vectors: a table, and a buffer. Of course, we're simplifying here; there are actually no vectors in the implementation. But this analogy is accurate enough.
In the background, the buffer stores our values in a sequential fashion. In the front, we have a table storing buckets that don't do much more than point to the element they stand for. When you insert a key-value pair, what happens is:
- The value gets put in the buffer.
- The key goes through a hashing function and becomes an index.
- The table creates a bucket at said index that points to the actual value:
The default hashing algorithm of the standard library has been chosen specifically to protect you from HashDoS attacks (https://cryptanalysis.eu/blog/2011/12/28/effective-dos-attacks-against-web-application-plattforms-hashdos/). If you want to squeeze out every bit of performance, you can do that, of your HashMap without caring about this particular risk, or you can specify a custom hasher by constructing it with with_hasher.