Open
Description
What it does
When an iterator is collected into vector, which is then push()
-ed into right after and then turned backed into iterator to do other things, it should be rewrite into a chain()
instead.
Advantage
- Make the code more readable
- Remove redudant allocations for better performance
Drawbacks
- Not sure if the compiler is smart enough to optimize it out
Example
fn collect_push_then_iter(iter: impl Iterator<Item = i32>) -> Vec<i32> {
let mut v = iter.collect::<Vec<_>>();
v.push(1);
v = v.into_iter().map(|x| x + 1).collect();
v
}
Could be written as:
fn collect_push_then_iter(iter: impl Iterator<Item = i32>) -> Vec<i32> {
iter.chain(std::iter::once(1)).map(|x| x + 1).collect()
}