[libcxx-commits] [libcxx] Optimize input_iterator-pair `insert` for std::vector (PR #113768)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Tue Jan 14 08:37:12 PST 2025


================
@@ -1250,30 +1250,29 @@ vector<_Tp, _Allocator>::__insert_with_sentinel(const_iterator __position, _Inpu
   difference_type __off = __position - begin();
   pointer __p           = this->__begin_ + __off;
   pointer __old_last    = this->__end_;
-  for (; this->__end_ != this->__cap_ && __first != __last; ++__first) {
+  for (; this->__end_ != this->__cap_ && __first != __last; ++__first)
     __construct_one_at_end(*__first);
+
+  if (__first == __last)
+    (void)std::rotate(__p, __old_last, this->__end_);
+  else {
+    __split_buffer<value_type, allocator_type&> __v(__alloc_);
----------------
ldionne wrote:

If we could have a heuristic of some kind here, we could pre-allocate `__v` to a given size and hope that we get lucky. That way, we might not have to reallocate memory for `__v`. Without a heuristic though, I think allocating the smallest amount of memory (what you have right now) is probably the best approach. It's worth thinking about whether such a heuristic exists.

```suggestion
    __split_buffer<value_type, allocator_type&> __v(__alloc_);
    __v.reserve(__recommend(capacity() + heuristic-maybe));
    // now if we got lucky, perhaps __v.capacity() is enough to hold (size() + (last-first)) elements
```

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


More information about the libcxx-commits mailing list