Skip to content

Commit 31389f9

Browse files
committed
perf: increase min buckets on very small types
Consider `HashSet<u8>` on x86_64 with SSE: | buckets | capacity | allocated bytes | | ------- | -------- | --------------- | | 4 | 3 | 36 | | 8 | 7 | 40 | | 16 | 14 | 48 | Quadroupling the number of buckets from 4 to 16 does not even increase the final allocation size by 50% (48/36=1.333). This is an edge case due to the padding of the control bytes. 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 4 -> 8 buckets leading to only 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: - x86_64 with SSE: 16 - aarch64: 8 This is a niche optimization. However, it also removes possible undefined behavior edge case in resize operations. In addition, it may be a useful property to utilize over-sized allocations (see rust-lang#523).
1 parent 8359365 commit 31389f9

File tree

1 file changed

+37
-16
lines changed

1 file changed

+37
-16
lines changed

src/raw/mod.rs

Lines changed: 37 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -192,16 +192,23 @@ impl ProbeSeq {
192192
// Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258
193193
#[cfg_attr(target_os = "emscripten", inline(never))]
194194
#[cfg_attr(not(target_os = "emscripten"), inline)]
195-
fn capacity_to_buckets(cap: usize) -> Option<usize> {
195+
fn capacity_to_buckets(cap: usize, table_layout: TableLayout) -> Option<usize> {
196196
debug_assert_ne!(cap, 0);
197197

198198
// For small tables we require at least 1 empty bucket so that lookups are
199-
// guaranteed to terminate if an element doesn't exist in the table.
200-
if cap < 8 {
199+
// guaranteed to terminate if an element doesn't exist in the table
200+
if cap < 8.max(table_layout.ctrl_align) {
201201
// We don't bother with a table size of 2 buckets since that can only
202-
// hold a single element. Instead we skip directly to a 4 bucket table
202+
// hold a single element. Instead, skip directly to a 4 bucket table
203203
// which can hold 3 elements.
204-
return Some(if cap < 4 { 4 } else { 8 });
204+
let min_buckets = if cap < 4 { 4 } else { 8 };
205+
206+
// Also ensure that buckets * table_layout.size is at least as big as
207+
// table_layout.ctrl_align. If it's not, then relatively quite a few
208+
// bytes are wasted padding to the alignment.
209+
let denominator = table_layout.size.max(1);
210+
let ratio = table_layout.ctrl_align / denominator;
211+
return Some(ratio.max(min_buckets));
205212
}
206213

207214
// Otherwise require 1/8 buckets to be empty (87.5% load)
@@ -1126,7 +1133,7 @@ impl<T, A: Allocator> RawTable<T, A> {
11261133
// elements. If the calculation overflows then the requested bucket
11271134
// count must be larger than what we have right and nothing needs to be
11281135
// done.
1129-
let min_buckets = match capacity_to_buckets(min_size) {
1136+
let min_buckets = match capacity_to_buckets(min_size, Self::TABLE_LAYOUT) {
11301137
Some(buckets) => buckets,
11311138
None => return,
11321139
};
@@ -1257,14 +1264,8 @@ impl<T, A: Allocator> RawTable<T, A> {
12571264
/// * If `self.table.items != 0`, calling of this function with `capacity`
12581265
/// equal to 0 (`capacity == 0`) results in [`undefined behavior`].
12591266
///
1260-
/// * If `capacity_to_buckets(capacity) < Group::WIDTH` and
1261-
/// `self.table.items > capacity_to_buckets(capacity)`
1262-
/// calling this function results in [`undefined behavior`].
1263-
///
1264-
/// * If `capacity_to_buckets(capacity) >= Group::WIDTH` and
1265-
/// `self.table.items > capacity_to_buckets(capacity)`
1266-
/// calling this function are never return (will go into an
1267-
/// infinite loop).
1267+
/// * If `self.table.items > capacity_to_buckets(capacity, Self::TABLE_LAYOUT)`
1268+
/// calling this function are never return (will loop infinitely).
12681269
///
12691270
/// See [`RawTableInner::find_insert_slot`] for more information.
12701271
///
@@ -1782,8 +1783,8 @@ impl RawTableInner {
17821783
// SAFETY: We checked that we could successfully allocate the new table, and then
17831784
// initialized all control bytes with the constant `EMPTY` byte.
17841785
unsafe {
1785-
let buckets =
1786-
capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?;
1786+
let buckets = capacity_to_buckets(capacity, table_layout)
1787+
.ok_or_else(|| fallibility.capacity_overflow())?;
17871788

17881789
let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?;
17891790
// SAFETY: We checked that the table is allocated and therefore the table already has
@@ -4566,6 +4567,26 @@ impl<T, A: Allocator> RawExtractIf<'_, T, A> {
45664567
mod test_map {
45674568
use super::*;
45684569

4570+
#[test]
4571+
fn test_minimum_capacity_for_small_types() {
4572+
#[track_caller]
4573+
fn test_t<T>() {
4574+
let raw_table: RawTable<T> = RawTable::with_capacity(1);
4575+
let actual_buckets = raw_table.buckets();
4576+
let min_buckets = Group::WIDTH / core::mem::size_of::<T>();
4577+
assert!(
4578+
actual_buckets >= min_buckets,
4579+
"expected at least {min_buckets} buckets, got {actual_buckets} buckets"
4580+
);
4581+
}
4582+
4583+
test_t::<u8>();
4584+
4585+
// This is only "small" for some platforms, like x86_64 with SSE, but
4586+
// there's no harm in running it on other platforms.
4587+
test_t::<u16>();
4588+
}
4589+
45694590
fn rehash_in_place<T>(table: &mut RawTable<T>, hasher: impl Fn(&T) -> u64) {
45704591
unsafe {
45714592
table.table.rehash_in_place(

0 commit comments

Comments
 (0)