[llvm] [ADT] Reduce memory allocation in SmallPtrSet::reserve() (PR #153126)
Kazu Hirata via llvm-commits
llvm-commits at lists.llvm.org
Mon Aug 11 19:57:36 PDT 2025
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/153126
Previously, reserve() allocated double the required number of buckets.
For example, for NumEntries in the range [49, 96], it would reserve
256 buckets when only 128 are needed to maintain the load factor.
This patch removes "+ 1" in the NewSize calculation.
>From 9ef803f9051a1bf0f90e53d60f35e5c93344ec06 Mon Sep 17 00:00:00 2001
From: Kazu Hirata <kazu at google.com>
Date: Mon, 11 Aug 2025 11:34:09 -0700
Subject: [PATCH] [ADT] Reduce memory allocation in SmallPtrSet::reserve()
Previously, reserve() allocated double the required number of buckets.
For example, for NumEntries in the range [49, 96], it would reserve
256 buckets when only 128 are needed to maintain the load factor.
This patch removes "+ 1" in the NewSize calculation.
---
llvm/include/llvm/ADT/SmallPtrSet.h | 2 +-
llvm/unittests/ADT/SmallPtrSetTest.cpp | 4 ++++
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/llvm/include/llvm/ADT/SmallPtrSet.h b/llvm/include/llvm/ADT/SmallPtrSet.h
index f0f28ac37761e..28a217afcd0a2 100644
--- a/llvm/include/llvm/ADT/SmallPtrSet.h
+++ b/llvm/include/llvm/ADT/SmallPtrSet.h
@@ -129,7 +129,7 @@ class SmallPtrSetImplBase : public DebugEpochBase {
// We must Grow -- find the size where we'd be 75% full, then round up to
// the next power of two.
size_type NewSize = NumEntries + (NumEntries / 3);
- NewSize = 1 << (Log2_32_Ceil(NewSize) + 1);
+ NewSize = 1 << Log2_32_Ceil(NewSize);
// Like insert_imp_big, always allocate at least 128 elements.
NewSize = std::max(128u, NewSize);
Grow(NewSize);
diff --git a/llvm/unittests/ADT/SmallPtrSetTest.cpp b/llvm/unittests/ADT/SmallPtrSetTest.cpp
index 4ea7403b65abc..a627091b90c70 100644
--- a/llvm/unittests/ADT/SmallPtrSetTest.cpp
+++ b/llvm/unittests/ADT/SmallPtrSetTest.cpp
@@ -475,4 +475,8 @@ TEST(SmallPtrSetTest, Reserve) {
EXPECT_EQ(Set.capacity(), 128u);
EXPECT_EQ(Set.size(), 6u);
EXPECT_THAT(Set, UnorderedElementsAre(&Vals[0], &Vals[1], &Vals[2], &Vals[3], &Vals[4], &Vals[5]));
+
+ // Reserving 192 should result in 256 buckets.
+ Set.reserve(192);
+ EXPECT_EQ(Set.capacity(), 256u);
}
More information about the llvm-commits
mailing list