-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Description
What it does
It warns about the issue described here.
TLDR: v.into_iter()...collect::<Vec<_>>()
can in general be optimized to run in-place and use v
's memory. But this means that, for example, v.into_iter().take(k).collect::<Vec<_>>()
will have len() = k
and capacity() = v.len()
. See playground example.
Clippy should warn about such patterns (the degree of generality remains open) and suggest applying shrink_to_fit
to the result or using different methods of extracting the desired values.
Advantage
The problematic code may result in unexpectedly high memory usage. The suggested changes (or even just raising awareness about this behavior) would prevent such scenarios.
Drawbacks
It's difficult to know exactly when the in-place optimization applies, so the user should manually check if the suggested change is needed in their case.
I guess it might be annoying for those who know the internal iterators well and expect this behavior.
Example
let b: Vec<_> = a.into_iter().take(5).collect();
Could be written as:
let b: Vec<_> = {
let mut b = a.into_iter().take(5).collect();
b.shrink_to_fit();
};
Although there are probably better options.
Comparison with existing lints
No response
Additional Context
No response