rust-lang / hashbrown

Rust port of Google's SwissTable hash map
https://rust-lang.github.io/hashbrown
Apache License 2.0
2.38k stars 275 forks source link

perf: increase min buckets on very small types #524

Open morrisonlevi opened 4 months ago

morrisonlevi commented 4 months ago

Consider HashSet<u8> on x86_64 with SSE with various bucket sizes and how many bytes the allocation ends up being:

buckets capacity allocated bytes
4 3 36
8 7 40
16 14 48
28 32 80

In general, doubling the number of buckets should roughly double the number of bytes used. However, for small bucket sizes for these small TableLayouts (4 -> 8, 8 -> 16), it doesn't happen. This is an edge case which happens because of padding of the control bytes and adding the Group::WIDTH. Taking the buckets from 4 to 16 (4x) only takes the allocated bytes from 36 to 48 (~1.3x).

This platform isn't the only one with edges. Here's aarch64 on an M1 for the same HashSet<u8>:

buckets capacity allocated bytes
4 3 20
8 7 24
16 14 40

Notice doubling from 4 to 8 buckets only lead to 4 more bytes (20 -> 24) instead of roughly doubling.

Generalized, buckets * table_layout.size needs to be at least as big as table_layout.ctrl_align. For the cases I listed above, we'd get these new minimum bucket sizes:

This is a niche optimization. However, it also removes possible undefined behavior edge case in resize operations. In addition, it would be a useful property when utilizing over-sized allocations (see rust-lang/hashbrown#523).

Amanieu commented 2 months ago

Also see #47 for previous discussion of this problem.