[libcxx-commits] [libcxx] [libc++] Optimize vector<bool>::resize() (PR #172853)

Nikolas Klauser via libcxx-commits libcxx-commits at lists.llvm.org
Thu Dec 18 06:10:18 PST 2025


https://github.com/philnik777 created https://github.com/llvm/llvm-project/pull/172853

None

>From 135b5f541dc80aaf727fbf2105a4984cb48922fd Mon Sep 17 00:00:00 2001
From: Nikolas Klauser <nikolasklauser at berlin.de>
Date: Thu, 18 Dec 2025 10:39:27 +0100
Subject: [PATCH] [libc++] Optimize vector<bool>::resize()

---
 libcxx/include/__vector/vector_bool.h         | 29 +++++++------------
 .../containers/sequence/vector_bool.bench.cpp |  9 ++++++
 2 files changed, 19 insertions(+), 19 deletions(-)

diff --git a/libcxx/include/__vector/vector_bool.h b/libcxx/include/__vector/vector_bool.h
index ccea5110e3870..f81fcd92a7e49 100644
--- a/libcxx/include/__vector/vector_bool.h
+++ b/libcxx/include/__vector/vector_bool.h
@@ -1050,25 +1050,16 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<bool, _Allocator>::swap(vector& __x)
 }
 
 template <class _Allocator>
-_LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<bool, _Allocator>::resize(size_type __sz, value_type __x) {
-  size_type __cs = size();
-  if (__cs < __sz) {
-    iterator __r;
-    size_type __c = capacity();
-    size_type __n = __sz - __cs;
-    if (__n <= __c && __cs <= __c - __n) {
-      __r = end();
-      __size_ += __n;
-    } else {
-      vector __v(get_allocator());
-      __v.reserve(__recommend(__size_ + __n));
-      __v.__size_ = __size_ + __n;
-      __r         = std::copy(cbegin(), cend(), __v.begin());
-      swap(__v);
-    }
-    std::fill_n(__r, __n, __x);
-  } else
-    __size_ = __sz;
+_LIBCPP_CONSTEXPR_SINCE_CXX20 void vector<bool, _Allocator>::resize(size_type __new_size, value_type __x) {
+  size_type __current_size = size();
+  if (__new_size < __current_size) {
+    __size_ = __new_size;
+    return;
+  }
+
+  reserve(__new_size);
+  std::fill_n(end(), __new_size - __current_size, __x);
+  __size_ = __new_size;
 }
 
 template <class _Allocator>
diff --git a/libcxx/test/benchmarks/containers/sequence/vector_bool.bench.cpp b/libcxx/test/benchmarks/containers/sequence/vector_bool.bench.cpp
index 68329cac8eb19..1300c600f57ad 100644
--- a/libcxx/test/benchmarks/containers/sequence/vector_bool.bench.cpp
+++ b/libcxx/test/benchmarks/containers/sequence/vector_bool.bench.cpp
@@ -68,4 +68,13 @@ static void BM_vector_bool_reserve(benchmark::State& state) {
 }
 BENCHMARK(BM_vector_bool_reserve)->Name("vector<bool>::reserve()");
 
+static void BM_vector_bool_resize(benchmark::State& state) {
+  for (auto _ : state) {
+    std::vector<bool> vec;
+    vec.resize(100);
+    benchmark::DoNotOptimize(vec);
+  }
+}
+BENCHMARK(BM_vector_bool_resize)->Name("vector<bool>::resize()");
+
 BENCHMARK_MAIN();



More information about the libcxx-commits mailing list