Skip to content

Warn that v.into_iter().take().collect::<Vec<_>>() might not release v's memory #15753

@mcalancea

Description

@mcalancea

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions