Repository navigation
Description
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
}
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) - 1comparisons 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
Add post: Why do we need C++ ranges
AlexGuteniev commentedon Aug 18, 2026
Looks like a duplicate of #1006
biart commentedon Aug 18, 2026
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:
IDL=2debug checks. This report is about extra dereferences in release builds where no debug checks run, and removing them wouldn't change the measurements.If anything, the #1006 discussion seems to support this report: the debug checks were already removed from
min/maxthere on the grounds that "it's a reasonable expectation forminormaxto 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.
biart commentedon Aug 18, 2026
Side note: I discovered that some machinery to fix this exists here:
STL/stl/inc/xutility
Line 7540 in 48570c4
I wonder if
_Prefer_iterator_copiescould be safely extended to somehow guess whether dereference may be costly. (Wheniter_reference_tis not a reference or specifically for transformed iterators)StephanTLavavej commentedon Sep 1, 2026
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.biart commentedon Sep 4, 2026
I naively thought that if
range_reference_t<R>andrange_value_t<R>is the same typeV, 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 objectV(so dereference is likely to create and fillVinside of it, so we pay thesizeof(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.
Benchmarks for the ranges::min/max/minmax value-vs-iterator heuristic
biart commentedon Sep 7, 2026
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_iteratorof custom size wrappingvector::iterator, then also some real ones that are smaller likeiotaor larger likedeque::iteratororjoiniterator from nested vectors) against elements of different sizes.fat_iteratoris 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):
sizeof(It)itervaluestlvector<double>min_elementvector<double> | transformdeque<double>vector<vector<double>> | joiniotatransformhere is a lambda with a small operation (multiply by constant for doubles) that returns a prvalue instead of forwarding.stlis better thanvalueonvector<double>due to vectorization, I have not disabled it.Then I decided to focus on values and more exhaustively search for any case where
itercan beatvalue. 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 vectorizedvalue-- 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 emulateiterwith an improved compiler, roughly what happens if DevCom-11139307 is fixedref1x-- novel, caching a handle to the element instead of the element, while dereferencing exactly once: a pointer whenRefis a reference (lvalue or rvalue), the value itself whenRefis a proxy or a prvalue ofV.All of them perform exactly
N - 1comparisons, so what distinguishes them is how many times they dereference. WithNthe number of elements andIthe number of times the running result is replaced:iter2N - 1*firstand*foundevery iteration, plus the final*founditerhoistN + I + 1*foundis kept in a registervalueN + I*firstwhen it improvesvalue1xNauto&&once and moves from itref1xNVIis aboutln Nfor random data,0when the first element already is the answer, andN - 1for the adverse ordering.The bench is run against a variety of patterns. The code is here.
To start with, the size of
Vseems 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:Things start breaking down only when
Vdoes not fit into a set of registers. It still favorsvalueon my machine for 128 bytes, and finallyiterwins for 256 bytes and above, whenVis spilled onto the stack. I admit that algorithms do not exist in a vacuum, so we need to consider a deliberately smaller limit onsizeof(V)when we design a heuristic, in order to free up some registers for the compiler.If we do
vector<V> | transformto return a large prvalue, the results are similar. This is the only case I found where ranges yielding a prvalue of typeVfavoriterovervalue/value1x.You can see above that
joinslightly favors caching iterators. Ironically, the current size heuristic caches values in this case. Withjoin | transform, however,iterimmediately loses any advantage. In fact, the following is true, at least on my machine and for any STL range I tried:When
Refis something else, the results still strongly favor caching values againstiter(but more ambiguous againstiterhoist). And again, there is no relation betweensizeof(V)and the caching performance difference, except for the hugeV.Finally, on differences between
value1xandvalue:valueis better when the materialization ofauto&& tmp = *firstis partly elidable, here are examples:valuevalue1xjoin | transform, adverse orderval128(reference), randomjoin, randomOtherwise
value1xis 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 thaniter, or eveniterhoist. However, if we want to be clever on this, then I propose the following improvements, ordered by importance: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.)valuetovalue1x. (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
minonly 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" → "storeRefas the result (reference_wrapperwhenRefis 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 initialranges::min/max/minmaximplementation (PR #916, commitc114d51, 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_elementdid not exist back then -- it arrived two years later in PR #2447 -- so the fact that this heuristic now decides whetherranges::minreaches a SIMD path (thevector<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_viewprefers iterator caching over value caching, according to the bench).Edit (2026-09-11):
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.ranges::minmax.I apologise for a link that were missing and for the lengthy text.