Skip to content

<algorithm>: ranges::min, ranges::max and ranges::minmax evaluate each element twice #6404

Open

Description

@biart

Describe the bug

std::ranges::min/max/minmax over a views::transform range invoke the transform roughly twice per element. libstdc++ invokes it once, and libc++'s count depends on the data. Since these overloads return range_value_t<R> by value and are constrained on indirectly_copyable_storable, one evaluation per element appears to be permitted.

Command-line test case

// cl /EHsc /std:c++latest /O2 repro.cpp
#include <algorithm>
#include <cstdio>
#include <ranges>
#include <vector>

int calls = 0;
struct Entry { double v; double get() const { ++calls; return v; } };

int main() {
    std::vector<Entry> data;
    for (int i = 1; i <= 8; ++i) data.push_back(Entry{static_cast<double>(i)});

    calls = 0;
    (void) std::ranges::min(data | std::views::transform(&Entry::get));
    std::printf("ranges::min    : %d\n", calls);   // 15

    calls = 0;
    double m = 1e300;
    for (const auto& e : data) m = (std::min)(m, e.get());
    std::printf("hand loop      : %d\n", calls);   // 8
}

Godbolt link

Observed (N = 8, so 8 is one call per element and 15 is 2N−1):

MS STL 19.51 libstdc++ libc++
ranges::min over transform_view 15 8 <=15
ranges::max over transform_view 15 8 <=15
ranges::minmax over transform_view 22 8 22
ranges::fold_left over transform_view 8 8 8
hand-written loop 8 8 8

Expected behavior

One evaluation per element, as libstdc++ achieves.

STL version

Microsoft Visual Studio 18 (Insiders), toolset 14.51.36231, compiler 19.51.36252, x64.

Additional context

[alg.min.max]/7 constrains comparisons and applications of the projection:

Complexity: Exactly ranges::distance(r) - 1 comparisons and twice as many applications of the projection, if any.

Here the projection is identity, and I could not find any wording in [alg.min.max] or [algorithms.requirements] that constrains how many times *i may be evaluated. An implementation that stores range_value_t<R> rather than tracking an iterator would satisfy the stated complexity exactly while halving the dereferences. minmax seems to be even more permissive with its "at most" wording.

Note that [alg.min.max]/27 has similar wording on the min_element variant, except that "if any" is suspiciously missing:

Complexity: Exactly max(last - first - 1,0) comparisons and twice as many projections.

I guess the pedantic reading of this gives the reason why min_element cannot have a similar optimisation (along with minor performance and design quirks on caching reference alongside of the iterator). This is deliberately not part of this report.

Measured impact

I was trying to write a blog post advocating for C++20 ranges, and ran into unexpected performance issues when using costly transform.

With a non-trivial transform (std::cos(angle) * length), MSVC 19.51 /O2: 2.09× a hand-written loop at N = 131072, and 4.77× at N = 2048. MSVC is not able to optimise out the redundancy at /O2 /Ob3 /GL /arch:AVX2 /LTCG or with /fp:fast.

If the maintainers consider this a worthwhile change, I would be happy to prepare a pull request for std::max/min/minmax with identity projection.

Activity

  1. AlexGuteniev commented on Aug 18, 2026

    @AlexGuteniev
    Contributor

    Looks like a duplicate of #1006

  2. biart commented on Aug 18, 2026

    @biart
    Author

    Thanks for the pointer, it indeed seems very related.

    I am trying to understand the discussion at #1006, and for now it feels that resolutions to both issues could be orthogonal:

    • <algorithm>: debug checks for predicates are observable #1006 is about extra predicate invocations by the IDL=2 debug checks. This report is about extra dereferences in release builds where no debug checks run, and removing them wouldn't change the measurements.
    • The call counter in the repro is only a measurement device; the motivating problem is the ~2× wall-clock cost with an expensive transform, which is why I'd frame this as QoI/performance rather than conformance.

    If anything, the #1006 discussion seems to support this report: the debug checks were already removed from min/max there on the grounds that "it's a reasonable expectation for min or max to invoke the predicate only once". Here we have the similar expectation, applied to dereferences.

    That said, I may well be missing context, so I rely on your expertise on how to track this. In the meanwhile, I will try to better understand both problems as well.

  3. biart commented on Aug 18, 2026

    @biart
    Author

    Side note: I discovered that some machinery to fix this exists here:

    concept _Prefer_iterator_copies = // When we have a choice, should we copy iterators or copy elements?

    I wonder if _Prefer_iterator_copies could be safely extended to somehow guess whether dereference may be costly. (When iter_reference_t is not a reference or specifically for transformed iterators)

  4. StephanTLavavej commented on Sep 1, 2026

    @StephanTLavavej
    Member

    I'd want to understand what scenarios copying iterators vs. copying elements is faster. The current heuristic requires sizeof(_It) <= 2 * sizeof(iter_value_t<_It>) (plus trivially copyable conditions), i.e. with 8-byte iterators, 4-byte+ elements are large enough to prefer iterator copies. That surprised me enough that I had to double check it; I expected to see the other way, where 4-byte and 8-byte elements would prefer element copies, and only 16-byte+ elements would be chonky enough to prefer iterator copies. However, I don't know what performance tuning went into the choice of this heuristic.

    This is relevant to your scenario since your double-storing element is 8-byte iterator-sized.

  5. biart commented on Sep 4, 2026

    @biart
    Author

    I naively thought that if range_reference_t<R> and range_value_t<R> is the same type V, then it always makes sense and "safer" to cache value rather than an iterator. This is because the dereference in this case is presumably responsible for creating a temporary object V (so dereference is likely to create and fill V inside of it, so we pay the sizeof(V) cost anyway). This is also safe in a sense that it does not touch the "normal" case of iterating over most things from C++17 or any container.

    However, after you pointed to the size heuristic, I feel this intuition is not as evident. Maybe I was even lucky with the libstdc++ by passing some similar size check with double. So I felt the need to check, found here that libstdc++ always, unconditionally, caches value for this kind of algorithms, even if it is heavy and returned by reference.

    The ultimate justification would be indeed to just bench a carefully selected bunch of different ranges. I will try to see how benchmarks are organized here and what is the benchmarking strategy. One caveat: the benchmarks on this may be not very faithful (and biased towards caching value in fact), because of MSVC compiler currently is not able to optimize repeating dereferences with transform, and even without, where it does not keep the result in register.

  6. biart commented on Sep 7, 2026

    @biart
    Author

    I (with help of LLM) prepared a benchmark here with various tests to understand/elaborate the value vs iterator heuristic.

    A caveat I stumbled upon, to remember: do not ever use default-generated <=> for benching custom values, it ruins the perf (see DevCom-10619302).

    First of all, I benchmarked iterators of various sizes (fat_iterator of custom size wrapping vector::iterator, then also some real ones that are smaller like iota or larger like deque::iterator or join iterator from nested vectors) against elements of different sizes. fat_iterator is empty padding, so it is always optimized away by the compiler, not interesting. Other iterator sizes are intertwined with more complex deref and increment, so not a clean bench, sadly. But my main observation is that iterator size for any imaginable STL iterator does not really affect performance. I mean... I could not come up with any situation where iterator size could give any reasonable signal to favor or not the heuristic in question.

    Here is a small excerpt from the table (times in ns, N = 8021):

    range sizeof(It) ref? iter value stl what the STL does
    vector<double> 8 ref 20560 1557 887 iter branch → vectorized min_element
    vector<double> | transform 16 prvalue 22456 1610 22456 iter branch, can't vectorize → 14× loss
    deque<double> 16 ref 29543 3098 29545 iter branch, can't vectorize → 9.5× loss
    vector<vector<double>> | join 24 ref 3000 3146 3275 value branch; iter would be 1.05× better
    iota 8 prvalue 4426 4424 4438 tie

    transform here is a lambda with a small operation (multiply by constant for doubles) that returns a prvalue instead of forwarding. stl is better than value on vector<double> due to vectorization, I have not disabled it.

    Then I decided to focus on values and more exhaustively search for any case where iter can beat value. Where values are large or with non-trivial copy, sure. But where else? I am testing several tracks here:

    • iter -- this is roughly the current implementation when the size heuristic is not passed, not vectorized
    • value -- this is the current implementation when the size heuristic is passed, not vectorized (if (*first < found) found = *first;, watch the double deref)
    • value1x -- libstdc++ implementation (auto&& tmp = *first; if (tmp < result) result = std::forward<decltype(tmp)>(tmp);)
    • iterhoist -- this is my attempt to emulate iter with an improved compiler, roughly what happens if DevCom-11139307 is fixed
    • ref1x -- novel, caching a handle to the element instead of the element, while dereferencing exactly once: a pointer when Ref is a reference (lvalue or rvalue), the value itself when Ref is a proxy or a prvalue of V.

    All of them perform exactly N - 1 comparisons, so what distinguishes them is how many times they dereference. With N the number of elements and I the number of times the running result is replaced:

    track dereferences why
    iter 2N - 1 *first and *found every iteration, plus the final *found
    iterhoist N + I + 1 the same, but *found is kept in a register
    value N + I re-dereferences *first when it improves
    value1x N binds auto&& once and moves from it
    ref1x N stores a handle or V

    I is about ln N for random data, 0 when the first element already is the answer, and N - 1 for the adverse ordering.

    The bench is run against a variety of patterns. The code is here.

    To start with, the size of V seems to have no effect on the result up to a certain point: caching values is nearly always better for containers of simple types. Here, for instance, results for a 64-byte struct:

    min/val64/random/iter/8021      8813 ns     8894 ns      89600 items_per_second=901.875M/s
    min/val64/random/value/8021     3076 ns     3069 ns     224000 items_per_second=2.61339G/s
    min/val64/random/value1x/8021   3052 ns     2999 ns     224000 items_per_second=2.67416G/s
    min/val64/random/iterhoist/8021 3100 ns     3139 ns     224000 items_per_second=2.55531G/s
    min/val64/random/stl/8021       8857 ns     8789 ns      74667 items_per_second=912.616M/s
    

    Things start breaking down only when V does not fit into a set of registers. It still favors value on my machine for 128 bytes, and finally iter wins for 256 bytes and above, when V is spilled onto the stack. I admit that algorithms do not exist in a vacuum, so we need to consider a deliberately smaller limit on sizeof(V) when we design a heuristic, in order to free up some registers for the compiler.

    If we do vector<V> | transform to return a large prvalue, the results are similar. This is the only case I found where ranges yielding a prvalue of type V favor iter over value/value1x.

    You can see above that join slightly favors caching iterators. Ironically, the current size heuristic caches values in this case. With join | transform, however, iter immediately loses any advantage. In fact, the following is true, at least on my machine and for any STL range I tried:

    When V is the same as Ref and V is smaller than 128 bytes, caching values is always the same or faster than caching iterators (even against the fixed iterhoist version).

    When Ref is something else, the results still strongly favor caching values against iter (but more ambiguous against iterhoist). And again, there is no relation between sizeof(V) and the caching performance difference, except for the huge V.

    Finally, on differences between value1x and value: value is better when the materialization of auto&& tmp = *first is partly elidable, here are examples:

    case value value1x ratio
    large prvalue 256 B, random 1710 12894 7.5×
    large prvalue 128 B, random 1815 7541 4.2×
    large prvalue 32 B, random 1475 2871 2.0×
    large prvalue 64 B, random 1647 3020 1.8×
    large prvalue 32 B, adverse order 1812 3008 1.7×
    large prvalue 64 B, adverse order 2280 3001 1.3×
    join | transform, adverse order 3416 4410 1.3×
    val128 (reference), random 2687 3088 1.2×
    join, random 3110 3355 1.1×

    Otherwise value1x is often faster.

    Summary

    Given that with C++20 a user can provide a deref of any arbitrary complexity, the safe and simple default would be value1x, unconditionally. For "normal" STL ranges it is usually no worse than iter, or even iterhoist. However, if we want to be clever on this, then I propose the following improvements, ordered by importance:

    1. Replace the current size heuristic with something like: Keep the current heuristic, but additionally cache values if !is_reference_v<Ref> && same_as<remove_cvref_t<Ref>, V> && sizeof(V) <= 32. (This one is never worse than the current way on my machine, a tie if MSVC improves the compiler, and safe for expensive transforms.)
    2. Add reference-yielding ranges with cheap-to-copy values to the same heuristic. (This one is even more tolerant to expensive user derefs, but the performance gain is ambiguous.)
    3. Switch value to value1x. (This one guarantees one deref per element. Attractive pros: more consistent with other stdlib implementations, and the only implementation whose cost is independent of the data.)

    I doubt that we should go for 3 right now~~, but 1 is a strict win and a very simple change. It consists of replacing the current heuristic with one backed by profiling (a one-liner), and adding the bench~~. I can open this PR if you think it is at least somewhat worthy.

    Note that I do not have access to other machines at home, so this is MSVC 19.51 x64 only -- no clang-cl, no ARM64, and min only in most rows.

    Discussion

    Just in case, I admit that !is_reference_v<Ref> is a strange heuristic, but it has some nice properties: it is backed by the bench easily, it scopes out all STL containers and pre-C++20 usage, and it uses a strong semantic hint that a "complex deref" usually results in a prvalue (not always, only a hint). This is part of the following reasoning chain: "minimize the number of iterator derefs in algorithms in C++20" → "store Ref as the result (reference_wrapper when Ref is a reference)" → "at least implement the prvalue part of this approach".

    And no bench could establish why that old heuristic existed. Maybe it is for some other architectures? So I tried to just blame the code, and found that it was added exactly as it stands today, with no explanation, in the initial ranges::min/max/minmax implementation (PR #916, commit c114d51, Casey Carter, June 2020). The concept text is identical to what is in <xutility> today, and none of the 22 review comments on that PR discuss it.

    Worth noting that vectorized min_element did not exist back then -- it arrived two years later in PR #2447 -- so the fact that this heuristic now decides whether ranges::min reaches a SIMD path (the vector<double> row above) looks accidental rather than intended.

    Finally, same_as<remove_cvref_t<Ref>, V> is there to keep caching iterators for proxies (without diving too deep into details: zip_view prefers iterator caching over value caching, according to the bench).


    Edit (2026-09-11):

    • Iterator size does matter today in fact: without the sizeof(_It) term, a 32-byte base+offset iterator has a 13× loss in iterator branch. So 1 has to narrow the heuristic, not replace it.
    • The 32-byte bound was a guess, not a measurement. Reevaluation needed for ranges::minmax.

    I apologise for a link that were missing and for the lengthy text.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    performanceranges

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions