Skip to content

Chained iterators cause 2x slowdown in micro-benchmark. #17764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mahkoh opened this issue Oct 4, 2014 · 4 comments
Closed

Chained iterators cause 2x slowdown in micro-benchmark. #17764

mahkoh opened this issue Oct 4, 2014 · 4 comments
Assignees
Labels
I-slow Issue: Problems and improvements with respect to performance of generated code.

Comments

@mahkoh
Copy link
Contributor

mahkoh commented Oct 4, 2014

Consider the following benchmark:

extern crate test;

fn init() -> [u8, ..1024] {
    let mut x: [u8, ..1024] = unsafe { std::mem::zeroed() };
    for i in range(0, x.len()) {
        x[i] = i as u8;
    }
    x
}

#[bench]
fn unrolled(b: &mut test::Bencher) {
    let x = init();
    b.iter(|| {
        for &y in x.iter() {
            test::black_box(y);
        }
        test::black_box(0u8);
    });
}

#[bench]
fn chained(b: &mut test::Bencher) {
    let x = init();
    b.iter(|| {
        for &y in x.iter().chain([0].iter()) {
            test::black_box(y);
        }
    });
}

And the results:

test chained  ... bench:      1889 ns/iter (+/- 2)
test unrolled ... bench:       956 ns/iter (+/- 1)
@thestinger thestinger added the I-slow Issue: Problems and improvements with respect to performance of generated code. label Oct 4, 2014
@huonw
Copy link
Member

huonw commented Oct 4, 2014

Is our generated code particularly bad, or is the implementation of chain slower than necessary?

For the most part, this seems like entirely expected and unavoidable behaviour: adding extra branches will make code slower.

@mahkoh
Copy link
Contributor Author

mahkoh commented Oct 4, 2014

A zero-cost chain could replace a loop with two chained iterators by two loops without chained iterators. Iterators are advertised as zero-cost and this code is more natural than two loops if the loop-body is non-trivial.

@mahkoh
Copy link
Contributor Author

mahkoh commented Oct 4, 2014

NB: I've seen this 2x slowdown in real programs that are not micro benchmarks.

@emberian emberian self-assigned this Mar 25, 2015
@mahkoh mahkoh closed this as completed Apr 10, 2015
@jonhoo
Copy link
Contributor

jonhoo commented Jan 23, 2017

#38038 would presumably address this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
I-slow Issue: Problems and improvements with respect to performance of generated code.
Projects
None yet
Development

No branches or pull requests

5 participants