[libcxx-commits] [libcxx] [libc++] Optimize string::erase (PR #223721)

via libcxx-commits libcxx-commits at lists.llvm.org
Wed Sep 16 03:18:45 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libcxx

Author: Nikolas Klauser (philnik777)

<details>
<summary>Changes</summary>

This change allows the `traits_type::move` (i.e. `memmove`) call to be tail-called, removing the need for allocating any stack space and a call. We also copy the null terminator through `memmove` instead of inserting it manually.

---
Full diff: https://github.com/llvm/llvm-project/pull/223721.diff


1 Files Affected:

- (modified) libcxx/include/string (+6-7) 


``````````diff
diff --git a/libcxx/include/string b/libcxx/include/string
index 8b0b648d2c655..861d3780c0f60 100644
--- a/libcxx/include/string
+++ b/libcxx/include/string
@@ -3273,13 +3273,12 @@ basic_string<_CharT, _Traits, _Allocator>::__erase_external_with_move(size_type
   if (__n == 0)
     return;
 
-  size_type __sz     = size();
-  value_type* __p    = __data();
-  __n                = std::min(__n, __sz - __pos);
-  size_type __n_move = __sz - __pos - __n;
-  if (__n_move != 0)
-    traits_type::move(__p + __pos, __p + __pos + __n, __n_move);
-  __null_terminate_at(__p, __sz - __n);
+  size_type __size = size();
+  value_type* __p  = __data();
+  __n              = std::min(__n, __size - __pos);
+  __set_size(__size - __n);
+  traits_type::move(__p + __pos, __p + __pos + __n, __size - __pos - __n + 1);
+  __annotate_shrink(__size);
 }
 
 template <class _CharT, class _Traits, class _Allocator>

``````````

</details>


https://github.com/llvm/llvm-project/pull/223721


More information about the libcxx-commits mailing list