[llvm] f90ded5 - [ADT] Reduce memory allocation in SmallPtrSet::reserve() (#153126)

via llvm-commits llvm-commits at lists.llvm.org
Mon Aug 11 22:51:35 PDT 2025


Author: Kazu Hirata
Date: 2025-08-11T22:51:32-07:00
New Revision: f90ded5b94edfb2d22064b4492ef569f70f60565

URL: https://github.com/llvm/llvm-project/commit/f90ded5b94edfb2d22064b4492ef569f70f60565
DIFF: https://github.com/llvm/llvm-project/commit/f90ded5b94edfb2d22064b4492ef569f70f60565.diff

LOG: [ADT] Reduce memory allocation in SmallPtrSet::reserve() (#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.

Added: 
    

Modified: 
    llvm/include/llvm/ADT/SmallPtrSet.h
    llvm/unittests/ADT/SmallPtrSetTest.cpp

Removed: 
    


################################################################################
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