[PATCH] D18344: Adjust initial size in StringMap constructor to guarantee no grow()

Mehdi AMINI via llvm-commits llvm-commits at lists.llvm.org
Mon Mar 21 23:15:35 PDT 2016


joker.eph created this revision.
joker.eph added a reviewer: dblaikie.
joker.eph added a subscriber: llvm-commits.

StringMap ctor accepts an initialize size, but expect it to be
rounded to the next power of 2. The ctor can handle that directly
instead of expecting clients to round it. Also, since the map will
resize itself when 75% full, take this into account an initialize
a larger initial size to avoid any growth.

http://reviews.llvm.org/D18344

Files:
  lib/Support/StringMap.cpp
  unittests/ADT/StringMapTest.cpp

Index: unittests/ADT/StringMapTest.cpp
===================================================================
--- unittests/ADT/StringMapTest.cpp
+++ unittests/ADT/StringMapTest.cpp
@@ -231,12 +231,12 @@
   // moved to a different bucket during internal rehashing. This depends on
   // the particular key, and the implementation of StringMap and HashString.
   // Changes to those might result in this test not actually checking that.
-  StringMap<uint32_t> t(1);
-  EXPECT_EQ(1u, t.getNumBuckets());
+  StringMap<uint32_t> t(0);
+  EXPECT_EQ(0u, t.getNumBuckets());
 
   StringMap<uint32_t>::iterator It =
     t.insert(std::make_pair("abcdef", 42)).first;
-  EXPECT_EQ(2u, t.getNumBuckets());
+  EXPECT_EQ(16u, t.getNumBuckets());
   EXPECT_EQ("abcdef", It->first());
   EXPECT_EQ(42u, It->second);
 }
Index: lib/Support/StringMap.cpp
===================================================================
--- lib/Support/StringMap.cpp
+++ lib/Support/StringMap.cpp
@@ -22,6 +22,13 @@
   
   // If a size is specified, initialize the table with that many buckets.
   if (InitSize) {
+    // The table will grow when the number of entries reach 3/4 of the number of
+    // buckets. To guarantee that "InitSize" number of entries can be inserted
+    // in the table without growing, we allocate just what is needed here.
+    InitSize = (InitSize * 4 + 2) / 3;
+    // Size has to be a power of 2
+    if (!isPowerOf2_32(InitSize))
+      InitSize = NextPowerOf2(InitSize);
     init(InitSize);
     return;
   }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D18344.51256.patch
Type: text/x-patch
Size: 1510 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20160322/0aea9f67/attachment.bin>


More information about the llvm-commits mailing list