Thomas Jung
Thomas Jung

Reputation: 33092

Using take on an iterator without copying

I had to replace

let mut bo = vec![];
try!(o.read_to_end(&mut bo));
let mut bo = bo.into_iter();
let vs : Vec<_> = (&mut bo).take(BUFFER).collect();
try!(io::stdout().write(&vs));

with this

let mut bo = vec![];
try!(o.read_to_end(&mut bo));
let mut io = 0;
let next = min(bo.len(), io + BUFFER);
try!(io::stdout().write(&bo[io..next]));

Using a slice was more than twice as fast as copying data into a Vec. Is there a way to use take(n) without copying?

Upvotes: 1

Views: 110

Answers (1)

Shepmaster
Shepmaster

Reputation: 431489

Iterator::take doesn't do any copying. Collecting the iterator into a vector, on the other hand, both allocates space and then moves items from the iterator into the collection.

Using a slice is the most idiomatic solution here. You have a contiguous range of bytes that you want to output in the vector, and slicing into that vector gives you an almost-free view into a range of those bytes.

Upvotes: 1

Related Questions