[libcxx-commits] [libcxx] [libc++] Optimize ranges::{for_each, for_each_n} for segmented iterators (PR #132896)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Wed Jun 4 09:58:59 PDT 2025


================
@@ -41,9 +43,14 @@ struct __for_each {
   template <class _Iter, class _Sent, class _Proj, class _Func>
   _LIBCPP_HIDE_FROM_ABI constexpr static for_each_result<_Iter, _Func>
   __for_each_impl(_Iter __first, _Sent __last, _Func& __func, _Proj& __proj) {
-    for (; __first != __last; ++__first)
-      std::invoke(__func, std::invoke(__proj, *__first));
-    return {std::move(__first), std::move(__func)};
+    if constexpr (!std::assignable_from<_Iter&, _Sent> && sized_sentinel_for<_Sent, _Iter>) {
----------------
ldionne wrote:

```suggestion
    // In the case where we have different iterator and sentinel types, the segmented iterator optimization
    // in std::for_each will not kick in. Therefore, we prefer std::for_each_n in that case (whenever we can
    // obtain the `n`).
    if constexpr (!std::assignable_from<_Iter&, _Sent> && sized_sentinel_for<_Sent, _Iter>) {
```

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


More information about the libcxx-commits mailing list