Skip to content

Slow performance of std::iter::Rev with iterator adapters using std::iter::Iterator::nth() #54054

Open
@koalatux

Description

@koalatux

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-iteratorsArea: IteratorsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.I-slowIssue: Problems and improvements with respect to performance of generated code.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions