Skip to content

<algorithm>: Taking advantage of LWG-4490 - #6477

Open
Cornea Cristian (cristi1990an) wants to merge 6 commits into
microsoft:mainfrom
cristi1990an:lwg-4490-move-copy-range-size
Open

Cornea Cristian (cristi1990an) wants to merge 6 commits into
microsoft:mainfrom
cristi1990an:lwg-4490-move-copy-range-size

Conversation

@cristi1990an

@cristi1990an Cornea Cristian (cristi1990an) commented Oct 5, 2026 •

Copy link
Copy Markdown

Some optimizations based on LWG-4490's new wording lenience.

Scope: tackle niche ranges that:
[-] are not common_ranges
[-] its end sentinel does not model sized_sentinel_for for the iterator type (sometimes required implicitly by exclusion)
[+] are themselves sized
[+] are random access

Steps:

  1. compute offsetted iterator based on the size of the range in O(1) time
  2. pass the new iterator pair further down the pipeline, making some ranges now eligible for existing optimized iterator-pair paths
  3. profit

Identified optimization opportunities in following algorithms:

  • ranges::copy
  • ranges::move
  • ranges::count
  • ranges::remove_copy
  • ranges::fill
  • ranges::replace
  • ranges::replace_copy
  • ranges::remove
  • ranges::unique
  • ranges::unique_copy
  • ranges::inmax_element (+ extra test coverage)
  • ranges::minmax (+ extra test coverage)
  • ranges::is_sorted_until
  • ranges::swap_ranges (+ extra test coverage)
  • ranges::uninitialized_copy (+ extra test coverage)
  • ranges::uninitialized_move (+ extra test coverage)
  • ranges::uninitialized_fill (+ extra test coverage)
  • ranges::uninitialized_value_construct
  • ranges::uninitialized_default_construct
  • ranges::destory (kinda, still possible to find the end iterator faster)

Actually implemented in this PR:

  • ranges::copy
  • ranges::move

Benchmark results for std::ranges::copy (median CPU time per call across five repetitions). It shows what I think is the expected cost distribution of memmove:

Input length Old New Change
0 B 2.30 ns 4.19 ns 82% slower (+1.89 ns)
1 B 2.44 ns 3.84 ns 57% slower (+1.40 ns)
8 B 3.84 ns 4.36 ns 14% slower (+0.52 ns)
64 B 15.17 ns 4.36 ns 3.48x speedup
512 B 105.79 ns 5.23 ns 20.23x speedup
4 KiB 784.74 ns 25.69 ns 30.55x speedup
32 KiB 6,510.42 ns 395.28 ns 16.47x speedup
64 KiB 13,020.83 ns 784.74 ns 16.59x speedup

Benchmark code included in PR for now, can remove or add more if requested.

AI used for identifying algorithms that could benefit from this optimization, overall code quality checks and benchmark design. Impacted tests were ran locally and are passing.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@cristi1990an Cornea Cristian (cristi1990an) changed the title Lwg 4490 move copy range size <algorithm>: Taking advantage of LWG-4490 Oct 5, 2026
@cristi1990an
Cornea Cristian (cristi1990an) marked this pull request as ready for review October 5, 2026 22:45
Copilot AI balanced review requested due to automatic review settings October 5, 2026 22:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The new ranges::destroy path can terminate when a valid sized range has a throwing size() operation.

Review effort: Balanced
Findings: 1 High severity

Open (1)
What changed in this PR

Optimizes sized, non-common random-access ranges by deriving an iterator end in constant time.

Changes:

  • Adds iterator-end derivation and applies optimized iterator-pair paths.
  • Expands targeted algorithm coverage.
  • Adds a ranges::copy benchmark.
File Description
stl/​inc/​xutility Adds the iterator-end helper.
stl/​inc/​algorithm Optimizes applicable range algorithms.
stl/​inc/​memory Optimizes uninitialized-memory and destruction algorithms.
tests/​std/​tests/​P0896R4_ranges_alg_uninitialized_value_construct/​test.cpp Tests the target range shape.
tests/​std/​tests/​P0896R4_ranges_alg_uninitialized_move/​test.cpp Tests optimized move behavior.
tests/​std/​tests/​P0896R4_ranges_alg_uninitialized_fill/​test.cpp Tests optimized fill behavior.
tests/​std/​tests/​P0896R4_ranges_alg_uninitialized_default_construct/​test.cpp Tests optimized default construction.
tests/​std/​tests/​P0896R4_ranges_alg_uninitialized_copy/​test.cpp Tests optimized copy behavior.
tests/​std/​tests/​P0896R4_ranges_alg_swap_ranges/​test.cpp Extends swap coverage.
tests/​std/​tests/​P0896R4_ranges_alg_minmax/​test.cpp Extends minmax coverage.
benchmarks/​src/​ranges_copy_sized_sentinel.cpp Benchmarks optimized copying.
benchmarks/​CMakeLists.txt Registers the benchmark.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread stl/inc/memory Resolved
@StephanTLavavej

Copy link
Copy Markdown
Member
  1. This PR is large (300+ lines) and touching our most template-complicated algorithms. I would prefer first-time contributors to start with smaller changes. (I have not yet had a chance to even review your <print>: Optimize no-argument print() brace handling #6465; making progress on the backlog is hard when people don't ask for advice about what changes would be helpful and what form they should take.) I apologize in advance for the bluntness but I am especially wary when new contributors are using AI to make large-scale changes, as they inherently lack the familiarity to judge whether changes are good or bad. I don't object to this PR's intent, but I want to see one algorithm updated, not all of them.
  2. Your table is calculating speedups incorrectly. Please read https://randomascii.wordpress.com/2018/02/04/what-we-talk-about-when-we-talk-about-performance/ which explains that the proper method is OldTime/NewTime expressed as a multiplicative factor; e.g. if something previously took 22 seconds and now takes 7 seconds, that's a 22/7 = 3.14x speedup. Describing that as "214% faster" is technically correct but extremely confusing (calculation: (OldTime/NewTime - 1) * 100 expressed as percent; describing a 1.23x speedup as "23% faster" is defensible but for speedups nearing 2x it is confusing and beyond 2x extremely confusing). Describing it as "68.2% faster" is simply wrong (bogus calculation: (1 - NewTime/OldTime) * 100 expressed as percent). Going from 13,020.83 ns to 784.74 ns is not "94.0% faster". That's an (impressive) 16.6x speedup.

@cristi1990an

Cornea Cristian (cristi1990an) commented Oct 6, 2026 •

Copy link
Copy Markdown
Author
  1. This PR is large (300+ lines) and touching our most template-complicated algorithms. I would prefer first-time contributors to start with smaller changes. (I have not yet had a chance to even review your <print>: Optimize no-argument print() brace handling #6465; making progress on the backlog is hard when people don't ask for advice about what changes would be helpful and what form they should take.) I apologize in advance for the bluntness but I am especially wary when new contributors are using AI to make large-scale changes, as they inherently lack the familiarity to judge whether changes are good or bad. I don't object to this PR's intent, but I want to see one algorithm updated, not all of them.
  2. Your table is calculating speedups incorrectly. Please read https://randomascii.wordpress.com/2018/02/04/what-we-talk-about-when-we-talk-about-performance/ which explains that the proper method is OldTime/NewTime expressed as a multiplicative factor; e.g. if something previously took 22 seconds and now takes 7 seconds, that's a 22/7 = 3.14x speedup. Describing that as "214% faster" is technically correct but extremely confusing (calculation: (OldTime/NewTime - 1) * 100 expressed as percent; describing a 1.23x speedup as "23% faster" is defensible but for speedups nearing 2x it is confusing and beyond 2x extremely confusing). Describing it as "68.2% faster" is simply wrong (bogus calculation: (1 - NewTime/OldTime) * 100 expressed as percent). Going from 13,020.83 ns to 784.74 ns is not "94.0% faster". That's an (impressive) 16.6x speedup.

No, no, that's perfectly valid. I was just particularly free these days and I wanted to do some contributions on parts of the STL that I'm more familiar with. I don't blindly open PRs, these two iessues were something that I wanted to work on for a long time now, and I don't plan on opening others any time soon.

Is it fine if I reduce the scope of the PR to only copy/move for now?

Copilot AI balanced review requested due to automatic review settings October 6, 2026 08:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

The implementation is focused and covered by existing range permutations; only a minor benchmark naming mismatch remains.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
Resolved since last review (1)

Comment thread benchmarks/CMakeLists.txt Resolved
Copilot AI balanced review requested due to automatic review settings October 6, 2026 09:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

Review effort: Lite
Findings: 1 High severity · 1 Medium severity

Open (2)
Resolved since last review (1)

Comment thread stl/inc/xutility Resolved
@YexuanXiao

Copy link
Copy Markdown
Contributor

Can the lambda be extracted into one or more helper functions? I noticed that many lambdas were added in your previous commit, and most of them appear to follow the same pattern. If possible, they should be extracted into helper functions instead of creating a lambda each time. https://github.com/cristi1990an/STL/commit/2ffee1edb18af9dc1767a62f574e1f22753a0dd7.diff

@cristi1990an

Cornea Cristian (cristi1990an) commented Oct 6, 2026 •

Copy link
Copy Markdown
Author

Can the lambda be extracted into one or more helper functions? I noticed that many lambdas were added in your previous commit, and most of them appear to follow the same pattern. If possible, they should be extracted into helper functions instead of creating a lambda each time. https://github.com/cristi1990an/STL/commit/2ffee1edb18af9dc1767a62f574e1f22753a0dd7.diff

Yes, I was thinking the same too. I had an alternative desing ready using a helper that returns an unwrapped begin and its best end (which may or may not remain the sentinel type). It would look something like this:

auto [_UFirst, _ULast] = _RANGES _Get_unwrapped_range(_Range);
return _Count_unchecked(_STD move(_UFirst), _STD move(_ULast), ...);

I initially dropped it while adopting even more algorithms from the list because I wanted to assert the constraints of each algorithm individually and I felt that the helper was hindering visiblity. I will audit all of them and see if a generic helper can still cover all of them.

Edit: I think "_Get_final_range_enpoints_unwrapped" would be a descriptive name for the helper

Copilot AI balanced review requested due to automatic review settings October 8, 2026 20:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@StephanTLavavej

This comment was marked as resolved.

@azure-pipelines

This comment was marked as resolved.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The implementation is consistent with existing range machinery and the relevant range configurations are covered by tests.

0 open findings

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 11, 2026 12:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The optimized path can reject valid differing wrapped and unwrapped difference types and lacks end-to-end algorithm coverage.

1 open finding
Previously missed (2)

In code that hasn't changed since last review

Medium severity Add end-to-end move test for unsized sentinel ranges

stl/​inc/​algorithm:2123

The new ranges::move path is not exercised end-to-end. The added tests invoke only the internal endpoint helper, and the move test matrix's random-access ranges use sized sentinels, so this branch is skipped. Add a range-overload test with a sized random-access range and unsized sentinel, checking moved values and the returned/rewrapped iterators.

Medium severity Add end-to-end copy test for unsized sentinel ranges

stl/​inc/​xutility:5357

The new ranges::copy path is not exercised end-to-end. The added machinery tests call the helper directly, while the copy test matrix's random-access ranges use sized sentinels, so this !sized_sentinel_for branch is skipped. Add a range-overload test using a sized random-access range with an unsized sentinel and verify copied values plus both returned iterators; a wrapped iterator would also cover rewrapping.

🧠 Review effort: Balanced

Comment thread stl/inc/xutility Resolved
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 5, 2026 16:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

An ambiguous ranges::next call introduces a compilation regression in ranges::copy and ranges::move for valid sized ranges whose iterator difference type also models a sentinel.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread stl/inc/xutility
template <random_access_iterator _It>
_NODISCARD constexpr _It _Get_final_iterator_unwrapped(const _It& _UFirst, const iter_difference_t<_It> _Distance) {
// Form the final iterator from a known distance.
return _RANGES next(_UFirst, _Distance);

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Must go faster ranges C++20/23 ranges

Projects

Status: Maintainer Review

Development

Successfully merging this pull request may close these issues.

4 participants