[all-commits] [llvm/llvm-project] 0298e5: [libc++] Optimize input_iterator-pair `insert` for...

Peng Liu via All-commits all-commits at lists.llvm.org
Tue Jan 14 08:40:51 PST 2025


  Branch: refs/heads/main
  Home:   https://github.com/llvm/llvm-project
  Commit: 0298e58c7dd1fa76b98ff270cdb9e0eba4949185
      https://github.com/llvm/llvm-project/commit/0298e58c7dd1fa76b98ff270cdb9e0eba4949185
  Author: Peng Liu <winner245 at hotmail.com>
  Date:   2025-01-14 (Tue, 14 Jan 2025)

  Changed paths:
    M libcxx/docs/ReleaseNotes/20.rst
    M libcxx/include/__vector/vector.h
    M libcxx/test/benchmarks/GenerateInput.h
    M libcxx/test/benchmarks/containers/ContainerBenchmarks.h
    M libcxx/test/benchmarks/containers/vector_operations.bench.cpp
    M libcxx/test/std/containers/sequences/vector/vector.modifiers/insert_iter_iter_iter.pass.cpp

  Log Message:
  -----------
  [libc++] Optimize input_iterator-pair `insert` for std::vector (#113768)

As a follow-up to #113852, this PR optimizes the performance of the
`insert(const_iterator pos, InputIt first, InputIt last)` function for
`input_iterator`-pair inputs in `std::vector` for cases where
reallocation occurs during insertion. Additionally, this optimization
enhances exception safety by replacing the traditional `try-catch`
mechanism with a modern exception guard for the `insert` function.

The optimization targets cases where insertion trigger reallocation. In
scenarios without reallocation, the implementation remains unchanged.

Previous implementation
-----------------------
The previous implementation of `insert` is inefficient in reallocation
scenarios because it performs the following steps separately:
- `reserve()`: This leads to the first round of relocating old
elements to new memory;
- `rotate()`: This leads to the second round of reorganizing the
existing elements;
- Move-forward: Moves the elements after the insertion position to
their final positions.
- Insert: performs the actual insertion.

This approach results in a lot of redundant operations, requiring the
elements to undergo three rounds of relocations/reorganizations to be
placed in their final positions.

Proposed implementation
-----------------------
The proposed implementation jointly optimize the above 4 steps in the
previous implementation such that each element is placed in its final
position in just one round of relocation. Specifically, this
optimization reduces the total cost from 2 relocations + 1 std::rotate
call to just 1 relocation, without needing to call `std::rotate`,
thereby significantly improving overall performance.



To unsubscribe from these emails, change your notification settings at https://github.com/llvm/llvm-project/settings/notifications


More information about the All-commits mailing list