[libcxx-commits] [libcxx] [libc++] Optimize vector assign for trivially copyable types (PR #233863)

Nikolas Klauser via libcxx-commits libcxx-commits at lists.llvm.org
Tue Oct 20 07:59:02 PDT 2026


https://github.com/philnik777 updated https://github.com/llvm/llvm-project/pull/233863

>From 20a91607c8d5e93f69005a6ff0b7b96b6a637038 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser <nikolasklauser at berlin.de>
Date: Tue, 20 Oct 2026 13:16:15 +0200
Subject: [PATCH] [libc++] Optimize vector assign for trivially copyable types

---
 libcxx/include/__vector/vector.h | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/libcxx/include/__vector/vector.h b/libcxx/include/__vector/vector.h
index 37a25f20e65cd4..8c31c253c5152e 100644
--- a/libcxx/include/__vector/vector.h
+++ b/libcxx/include/__vector/vector.h
@@ -968,6 +968,25 @@ template <class _AlgPolicy, class _Iterator>
 _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI void
 vector<_Tp, _Allocator>::__assign_with_size(_Iterator __first, difference_type __n) {
   size_type __new_size = static_cast<size_type>(__n);
+
+#ifndef _LIBCPP_CXX03_LANG
+  if constexpr (is_same<value_type, __policy_value_type<_AlgPolicy, _Iterator>>::value &&
+                __allocator_has_trivial_move_construct_v<allocator_type, value_type> &&
+                __allocator_has_trivial_destroy_v<allocator_type, value_type> &&
+                is_trivially_copyable<value_type>::value && __libcpp_is_contiguous_iterator<_Iterator>::value) {
+    if (!__libcpp_is_constant_evaluated()) {
+      if (__new_size > capacity()) {
+        __vdeallocate();
+        __vallocate(__recommend(__new_size));
+      }
+
+      std::__constexpr_memmove(
+          std::__to_address(__layout_.__begin_ptr()), std::__to_address(__first), __element_count(__new_size));
+      __layout_.__set_bound_using_pointer(__layout_.__begin_ptr() + __new_size);
+    }
+  }
+#endif
+
   if (__new_size <= capacity()) {
     auto const __size = size();
     if (__new_size > __size) {



More information about the libcxx-commits mailing list