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

Peng Liu via libcxx-commits libcxx-commits at lists.llvm.org
Tue Mar 25 07:11:56 PDT 2025


================
@@ -10,7 +10,11 @@
 #ifndef _LIBCPP___ALGORITHM_FOR_EACH_N_H
 #define _LIBCPP___ALGORITHM_FOR_EACH_N_H
 
+#include <__algorithm/for_each.h>
----------------
winner245 wrote:

Thank you for bringing up this into attention! I actually thought about the structure and relationship of these 4 algorithms: `std::for_each`, `std::for_each_n`,  `std::ranges::for_each`, `std::ranges::for_each_n`. Previously, segmented iterator optimization was added only for `std::for_each`, but not for the rest 3 algorithms. So the simplest approach to enable segmented iterator optimizations for the other 3 algorithms seems to be forwarding to `for_each`. The benefit of doing so is that we only needs to maintain one optimization logic in one place. I can also `#include  <__algorithm/for_each_segment.h>` in the 3 algorithms, then each of them has to implement the same boilerplate, such as wrapping the function using `__movable_box` and then use `__for_each_segment` to invoke the respective `for_each` functions for each segment. This results in 4 nearly the same optimization logics. With this in mind, my initial choice was to forward to `std::for_each` (I still need to fix `std::ranges::for_each_n` to forward to `std::for_each`; it currently forwards to `std::ranges::for_each`), as is suggested in the issue #102817 description. It seems that @philnik777 favors the forwarding approach. Please let me know if you have different opinions or concerns,  and I am flexible on this. 

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


More information about the libcxx-commits mailing list