HashMap meory usage, new_in()

I need to track and limit memory usage in a HashMap. I'm having a rough time figuring out how to do it.

My current thought is to use an allocator like bumpalo, along with a HashMap implementation that has a .new_in() function to assign a custom allocator. I see that the old HashBrown crate has such a function.


Is there a way to track memory usage of the existing, built-in HashMap? I need not only the usage of the HashMap itself, but also the keys and values.

When HashBrown was ported to the standard library, why didn't they also include new_in()?

Is there a better way to measure HashMap memory usage?

You can't do that even with HashMap::new_in from hashbrown. The keys and values decide themself where to allocate memory if they need it. You'll have to use custom types that track the memory used for keys and values too.

hashbrown has not been ported to the standard library, rather the standard library depends on the hashbrown crate.

new_in has been added to hashbrown after the stdlib added its dependency on hashbrown, so they couldn't have included it at that time. It has been added to hashbrown as part of rust-lang/wg-allocators#7 but nobody added it to the stdlib's HashMap wrapper yet. It looks like the progress has kinda stalled due to the possibility of having a better API. If you really need it you could make a PR to add it to the stdlib.

1 Like