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

Add ParallelIterator::collect_vec_list #1128

Merged
merged 5 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/iter/collect/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::LinkedList;

use super::{IndexedParallelIterator, ParallelIterator};

mod consumer;
Expand Down Expand Up @@ -64,6 +66,24 @@ where
});
}

/// Collects the iterator into a linked list of vectors.
///
/// This is called by `ParallelIterator::collect_vec_list`.
pub(super) fn collect_vec_list<I>(pi: I) -> LinkedList<Vec<I::Item>>
where
I: ParallelIterator,
{
match pi.opt_len() {
Some(len) => {
// Pseudo-specialization. See impl of ParallelExtend for Vec for more details.
let mut v = Vec::new();
Copy link

Choose a reason for hiding this comment

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

Suggested change
let mut v = Vec::new();
let mut v = Vec::with_capacity(len);

Copy link
Member

Choose a reason for hiding this comment

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

This suggested change is fine, but I think it won't really matter since special_extend -> collect_with_consumer will call reserve anyway. Allocate now or later, but we're still only doing it once.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Right, that was my thinking, and the ParallelExtend impl doesn't reserve here either.

super::collect::special_extend(pi, len, &mut v);
LinkedList::from([v])
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Wasn't sure if I should re-use pi.collect::<Vec<_>>() here or not; theoretically that'd have an unnecessary second check of opt_len() but that would get optimized in almost all cases.

Copy link
Member

Choose a reason for hiding this comment

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

The way you've done it is fine, especially since that internal method is already shared pub(super).

The other thing I noticed is that the unindexed case avoids pushing empty vecs to the list, but here it will always create that one node. I'm not sure that matters though -- it's potentially more meaningful when there could end up being many empty list nodes, instead of just this one in a degenerate case.

}
None => super::extend::drive_list_vec(pi),
}
}

/// Create a consumer on the slice of memory we are collecting into.
///
/// The consumer needs to be used inside the scope function, and the
Expand Down
13 changes: 9 additions & 4 deletions src/iter/extend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ use std::hash::{BuildHasher, Hash};
/// parallel, then extending the collection sequentially.
macro_rules! extend {
($self:ident, $par_iter:ident, $extend:ident) => {
$extend(
$self,
$par_iter.into_par_iter().drive_unindexed(ListVecConsumer),
);
$extend($self, drive_list_vec($par_iter));
};
}

Expand All @@ -24,6 +21,14 @@ fn len<T>(list: &LinkedList<Vec<T>>) -> usize {
list.iter().map(Vec::len).sum()
}

pub(super) fn drive_list_vec<I, T>(pi: I) -> LinkedList<Vec<T>>
where
I: IntoParallelIterator<Item = T>,
T: Send,
{
pi.into_par_iter().drive_unindexed(ListVecConsumer)
}

struct ListVecConsumer;

struct ListVecFolder<T> {
Expand Down
36 changes: 36 additions & 0 deletions src/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ use self::plumbing::*;
use self::private::Try;
pub use either::Either;
use std::cmp::{self, Ordering};
use std::collections::LinkedList;
use std::iter::{Product, Sum};
use std::ops::{Fn, RangeBounds};

Expand Down Expand Up @@ -2339,6 +2340,41 @@ pub trait ParallelIterator: Sized + Send {
SkipAnyWhile::new(self, predicate)
}

/// Collects this iterator into a linked list of vectors.
///
/// This is useful when you need to condense a parallel iterator into a collection,
/// but have no specific requirements for what that collection should be. If you
/// plan to store the collection longer-term, `Vec<T>` is, as always, likely the
/// best default choice, despite the overhead that comes from concatenating each
/// vector. Or, if this is an `IndexedParallelIterator`, you should also prefer to
/// just collect to a `Vec<T>`.
///
/// Internally, most [`FromParallelIterator`]/[`ParallelExtend`] implementations
/// use this strategy; each job collecting their chunk of the iterator to a `Vec<T>`
/// and those chunks getting merged into a `LinkedList`, before then extending the
/// collection with each vector. This is the most efficient way to collect an
/// unindexed parallel iterator (again, indexed parallel iterators can be
/// efficiently collected simply into a vector).
coolreader18 marked this conversation as resolved.
Show resolved Hide resolved
///
/// # Examples
///
/// ```
/// # use std::collections::LinkedList;
/// use rayon::prelude::*;
///
/// let result: LinkedList<Vec<_>> = (0..=100)
/// .into_par_iter()
/// .filter(|x| x % 2 == 0)
/// .flat_map(|x| 0..x)
/// .collect_vec_list();
///
/// let total_len = result.iter().flatten().count();
/// assert_eq!(total_len, 2550);
/// ```
fn collect_vec_list(self) -> LinkedList<Vec<Self::Item>> {
collect::collect_vec_list(self)
}

/// Internal method used to define the behavior of this parallel
/// iterator. You should not need to call this directly.
///
Expand Down