Is collecting a Iter<_> into Vec<_> costly? or is this zero-cost? and vice versa?

63 points bxsx0074 33 comments

Hi I am wondering if it makes more sense, for example, for a util function to return an iterator or a Vec<> if given the choice. Let's say the caller function might use the returned Vec<> as is, or actually do result.iter().map() again.

for example:


fn a() -> Vec<i32> {  
//// do something here to get a iterator  
iterator.collect()  
}

fn b() {  
let result: Vec<i32> = a();  
let new_result: Vec<i32> = 
    result.iter().map(|x| { x + 1 }).collect();  
}

Would the Iter -> collect::Vec<\_>() -> Vec<\_> -> Iter -> Mapped be very costly? or are these part of thezero cost abstractions of rust?
If returning an iterator is more efficient, do I have to decide on whether to return a IntoIter or Iter from within the called function and let the calling function decide?