Skip to content
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

optimize implementation of Zip::fold and company #100124

Closed
wants to merge 4 commits into from

Conversation

sarah-ek
Copy link

@sarah-ek sarah-ek commented Aug 3, 2022

adds a more efficient implementation of core::iter::Zip::{fold, rfold, try_fold, try_rfold}
on my machine, this gives a 15% speedup on the iter::bench_skip_cycle_skip_zip_add_sum benchmark, and a 32% speedup on iter::bench_skip_then_zip.

i haven't noticed any performance regressions

@rust-highfive
Copy link
Collaborator

Thanks for the pull request, and welcome! The Rust team is excited to review your changes, and you should hear from @m-ou-se (or someone else) soon.

Please see the contribution instructions for more information.

@rustbot
Copy link
Collaborator

rustbot commented Aug 3, 2022

Hey! It looks like you've submitted a new PR for the library teams!

If this PR contains changes to any rust-lang/rust public library APIs then please comment with @rustbot label +T-libs-api -T-libs to tag it appropriately. If this PR contains changes to any unstable APIs please edit the PR description to add a link to the relevant API Change Proposal or create one if you haven't already. If you're unsure where your change falls no worries, just leave it as is and the reviewer will take a look and make a decision to forward on if necessary.

Examples of T-libs-api changes:

  • Stabilizing library features
  • Introducing insta-stable changes such as new implementations of existing stable traits on existing stable types
  • Introducing new or changing existing unstable library APIs (excluding permanently unstable features / features without a tracking issue)
  • Changing public documentation in ways that create new stability guarantees
  • Changing observable runtime behavior of library APIs

@rustbot rustbot added the T-libs Relevant to the library team, which will review and decide on the PR/issue. label Aug 3, 2022
@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Aug 3, 2022
Copy link
Contributor

@timvermeulen timvermeulen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an excellent first contribution 👍

I've left some initial feedback. Zip is weird in the sense that it needs to choose which inner iterator to iterate internally and which one externally, but to me choosing the first one to iterate internally seems like a very reasonable choice.

Comment on lines 257 to 299
#[inline]
default fn fold<T, F>(self, init: T, mut f: F) -> T
where
F: FnMut(T, Self::Item) -> T,
{
let mut a = self.a;
let mut b = self.b;

let acc = a.try_fold(init, move |acc, x| match b.next() {
Some(y) => Ok(f(acc, (x, y))),
None => Err(acc),
});

match acc {
Ok(exhausted_a) => exhausted_a,
Err(exhausted_b) => exhausted_b,
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a fold implementation can't be implemented on top of an inner fold, it's common in libcore to delegate to self's try_fold instead in order to avoid some duplicate logic. See e.g. Take::fold. TakeWhile, MapWhile, and Scan do the same thing. You could see if it affects benchmark results in any way, but I'd hope that it won't.

SIde note: closures in the implementation of iterator adapters are typically not written outright, but returned from a nested function, see #62429.

Comment on lines 285 to 294
let acc = a.try_fold(init, move |acc, x| match b.next() {
Some(y) => {
let result = f(acc, (x, y));
match result.branch() {
ControlFlow::Continue(continue_) => Ok(continue_),
ControlFlow::Break(break_) => Err(R::from_residual(break_)),
}
}
None => Err(R::from_output(acc)),
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This pattern of either continuing with an output value or breaking with an output value or a residual value can be expressed a lot simpler by the ControlFlow enum, and specifically its (non-public) from_try and into_try methods. Take::try_fold illustrates this really well.

Comment on lines 302 to 319
#[inline]
default fn rfold<T, F>(mut self, init: T, mut f: F) -> T
where
A: DoubleEndedIterator + ExactSizeIterator,
B: DoubleEndedIterator + ExactSizeIterator,
F: FnMut(T, Self::Item) -> T,
{
self.adjust_back();
let mut a = self.a;
let mut b = self.b;

let acc = a.try_rfold(init, move |acc, x| match b.next_back() {
Some(y) => Ok(f(acc, (x, y))),
None => Err(acc),
});

match acc {
Ok(exhausted_a) => exhausted_a,
Err(exhausted_b) => exhausted_b,
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we know that the inner iterators have the same length (after adjusting), so it might be worth writing this in terms of self.a.rfold instead. We'd have to panic in case b.next_back returns None. I have not benchmarked this, but in theory rfold might lead to more efficient machine code, depending on the underlying iterator.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this gave me the idea of applying a similar optimization to fold. by checking if both iterators have the same length (which i assumed is a common case for zip), we can use a.fold instead of a.try_fold

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very cool! I didn't think about doing that with size_hint.

@sarah-ek
Copy link
Author

sarah-ek commented Aug 4, 2022

thanks for the feedback! i've applied your suggestions to the code, and additionally made some further optimizations. (though they don't show a difference on the current zip benchmarks, which are somewhat limited)

Copy link
Member

@the8472 the8472 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there tests that target the new unsafe TrustedRandomAccess implementations? If not we need them because that particular specialization has a long history of unsoundness.

library/core/src/iter/adapters/zip.rs Outdated Show resolved Hide resolved
@sarah-ek sarah-ek requested a review from the8472 August 10, 2022 13:53
library/core/src/iter/adapters/zip.rs Outdated Show resolved Hide resolved
library/core/src/iter/adapters/zip.rs Outdated Show resolved Hide resolved
library/core/src/iter/adapters/zip.rs Outdated Show resolved Hide resolved
@sarah-ek
Copy link
Author

i've applied the previous suggestions. i tried to rebase on the master branch to be able to get relevant comparisons from benchmarks. i hope i didn't mess up any git stuff

@JohnCSimon JohnCSimon added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Oct 8, 2022
@saethlin
Copy link
Member

I'm curious
@bors try @rust-timer queue

@rust-timer
Copy link
Collaborator

Awaiting bors try build completion.

@rustbot label: +S-waiting-on-perf

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Dec 28, 2022
@rust-log-analyzer
Copy link
Collaborator

The job dist-x86_64-linux failed! Check out the build log: (web) (plain)

Click to see the possible cause of the failure (guessed by this bot)
   Compiling profiler_builtins v0.0.0 (/checkout/library/profiler_builtins)
[RUSTC-TIMING] build_script_build test:false 0.159
[RUSTC-TIMING] build_script_build test:false 0.199
[RUSTC-TIMING] build_script_build test:false 0.432
error[E0599]: no function or associated item named `wrap_mut_2` found for struct `NeverShortCircuit` in the current scope
    |
    |
251 | / macro_rules! zip_impl_general_defaults {
252 | |     () => {
253 | |         default fn new(a: A, b: B) -> Self {
254 | |             Zip {
...   |
298 | |             ZipImpl::try_fold(&mut self, init, NeverShortCircuit::wrap_mut_2(f)).0
    | |                                                                   |
    | |                                                                   |
    | |                                                                   function or associated item not found in `NeverShortCircuit<_>`
    | |                                                                   help: there is an associated function with a similar name: `wrap_mut_2_imp`
332 | |     };
333 | | }
333 | | }
    | |_- in this expansion of `zip_impl_general_defaults!`
...
344 |       zip_impl_general_defaults! {}
    |
   ::: library/core/src/ops/try_trait.rs:379:1
    |
    |
379 |   pub(crate) struct NeverShortCircuit<T>(pub T);
    |   -------------------------------------- function or associated item `wrap_mut_2` not found for this struct

error[E0599]: no function or associated item named `wrap_mut_2` found for struct `NeverShortCircuit` in the current scope
    |
    |
251 | / macro_rules! zip_impl_general_defaults {
252 | |     () => {
253 | |         default fn new(a: A, b: B) -> Self {
254 | |             Zip {
...   |
298 | |             ZipImpl::try_fold(&mut self, init, NeverShortCircuit::wrap_mut_2(f)).0
    | |                                                                   |
    | |                                                                   |
    | |                                                                   function or associated item not found in `NeverShortCircuit<_>`
    | |                                                                   help: there is an associated function with a similar name: `wrap_mut_2_imp`
332 | |     };
333 | | }
333 | | }
    | |_- in this expansion of `zip_impl_general_defaults!`
...
377 |       zip_impl_general_defaults! {}
    |
   ::: library/core/src/ops/try_trait.rs:379:1
    |
    |
379 |   pub(crate) struct NeverShortCircuit<T>(pub T);
    |   -------------------------------------- function or associated item `wrap_mut_2` not found for this struct
For more information about this error, try `rustc --explain E0599`.
[RUSTC-TIMING] core test:false 7.338
error: could not compile `core` due to 2 previous errors
warning: build failed, waiting for other jobs to finish...

@bors
Copy link
Contributor

bors commented Dec 28, 2022

💔 Test failed - checks-actions

@bors bors added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Dec 28, 2022
@saethlin
Copy link
Member

Whelp, that didn't work, but that also means it would have failed when approved anyway. @sarah-ek can you rebase this again and see if you can fix the compile error that appears?

@JohnCSimon
Copy link
Member

@sarah-ek
ping from triage - can you post your status on this PR? There hasn't been an update in a few months. Thanks!

FYI: when a PR is ready for review, send a message containing
@rustbot ready to switch to S-waiting-on-review so the PR is in the reviewer's backlog.

@bors
Copy link
Contributor

bors commented Feb 13, 2023

☔ The latest upstream changes (presumably #107634) made this pull request unmergeable. Please resolve the merge conflicts.

@Dylan-DPC Dylan-DPC removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Feb 22, 2023
@Dylan-DPC
Copy link
Member

Closing this as inactive. Feel free to reöpen this pr or create a new pr if you get the time to work on this. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-libs Relevant to the library team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.