Can I offer a vector early instead of get one from rayon::iter_mut().map().collect()?

For example, I wrote like this:

let mut v: Vec<usize> = (0..10).into_par_iter().collect();

If I then push an extra element into v, it will probably trigger an alloc and copy operation.

So,

  1. Can I somehow hint rayon about the vector size it collects?
  2. What's more, can I even give rayon a vector and do the same thing?

I think your are looking for IndexedParallelIterator::collect_into_vec:

use rayon::prelude::*;

fn main() {
    let mut v = Vec::with_capacity(12);
    
    (0..10).into_par_iter().collect_into_vec(&mut v);
}

Playground.

4 Likes

Thanks a lot.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.