-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Description
The following example shows a benchmark of the iterator adapter step_by(). Once using step_by() directly on the range and once with a redirection via rev().
use test::Bencher;
#[bench]
fn bench_forward_skip(b: &mut Bencher) {
b.iter(|| (0..10001).step_by(100).sum::<i32>());
}
#[bench]
fn bench_reverse_skip(b: &mut Bencher) {
b.iter(|| (0..10001).rev().step_by(100).sum::<i32>());
}Running this benchmark with the current nightly shows these results:
test tests::bench_forward_skip ... bench: 137 ns/iter (+/- 6)
test tests::bench_reverse_skip ... bench: 3,878 ns/iter (+/- 327)
step_by() makes use of nth() of the adapted iterator. A range provides an optimized version of nth(), but by using rev() we get to use the default implementation of nth().
We should Extend std::iter::DoubleEndedIterator to provide a new method maybe nth_back() or rnth() with a default implementation which then can get adapted by rev(). Similar to the already existing next_back(), try_rfold(), rfold() and rfind().
Update:
nth_back() has been merged in #56802. Types which have a specialized nth() and implement DoubleEndedIterator are candidates for a specialized nth_back(). The following list shows these candidates and their implementation status:
- Box (Implement specialized nth_back() for Box and Windows. #59328)
- Bytes (implement specialized nth_back() for Bytes, Fuse and Enumerate #60023)
- Chain (Add custom nth_back for Chain #60492)
- Chunks (Feature/nth back chunks #61048)
- ChunksExact (nth_back for chunks_exact #62064)
- ChunksExactMut (Implement
nth_backfor ChunksExactMut #63265) - ChunksMut (squash of all commits for nth_back on ChunksMut #62074)
- &mut DoubleEndedIterator (Add DoubleEndedIterator::nth_back #56802)
- Enumerate (implement specialized nth_back() for Bytes, Fuse and Enumerate #60023)
- Fuse (default fn) (implement specialized nth_back() for Bytes, Fuse and Enumerate #60023)
- Fuse (where FusedIterator) (implement specialized nth_back() for Bytes, Fuse and Enumerate #60023)
- slice::Iter (defined by a macro) (Implement nth_back for slice::{Iter, IterMut} #60772)
- slice::IterMut (defined by a macro) (Implement nth_back for slice::{Iter, IterMut} #60772)
- Range (implement nth_back for Range(Inclusive) #61671)
- RangeInclusive (implement nth_back for Range(Inclusive) #61671)
- RChunks (Implement nth_back for RChunks(Exact)(Mut) #60555)
- RChunksExact (Implement nth_back for RChunks(Exact)(Mut) #60555)
- RChunksExactMut (Implement nth_back for RChunks(Exact)(Mut) #60555)
- RChunksMut (Implement nth_back for RChunks(Exact)(Mut) #60555)
- Rev (Add DoubleEndedIterator::nth_back #56802)
- Skip (Add custom nth_back to Skip #60454)
- Windows (Implement specialized nth_back() for Box and Windows. #59328)
- Zip
- Zip (in ZipImpl default fn)
- Zip (in ZipImpl where TrustedRandomAccess)