rust-lang / rust-lang/rust-clippy

new perf lint: use conditional Vec::with_capacity() when conditionally pushing elements one by one

Open
#3,040 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

original rustc ticket: https://github.com/rust-lang/rust/issues/52495

code:

fn main() {
    foo(false);
}

fn foo(yes: bool) {
    let mut x = Vec::new();
    println!("capacity: {}", x.capacity());
    println!("length : {}", x.len());
    println!("pushing data");
    if yes {
	x.push(1);
        x.push(2);
        x.push(3);
        x.push(4);
    } else {
        x.push(1);
        x.push(2);
        x.push(3);
        x.push(4);
        x.push(5);
        x.push(6);
    }
    println!("capacity: {}", x.capacity());
    println!("length : {}", x.len());
    println!("vec: {:?}", x);
}

current output:

capacity: 0
length : 0
pushing data
capacity: 8
length : 6
vec: [1, 2, 3, 4, 5, 6]

the lint could suggest to use Vec::with_capacity() conditionally:

    let mut x = Vec::with_capacity(if yes { 4 } else { 6 });
fn main() {
    foo(false);
}

fn foo(yes: bool) {
    let mut x = Vec::with_capacity(if yes { 4 } else { 6 });
    println!("capacity: {}", x.capacity());
    println!("length : {}", x.len());
    println!("pushing data");
    if yes {
	x.push(1);
        x.push(2);
        x.push(3);
        x.push(4);
    } else {
        x.push(1);
        x.push(2);
        x.push(3);
        x.push(4);
        x.push(5);
        x.push(6);
    }
    println!("capacity: {}", x.capacity());
    println!("length : {}", x.len());
    println!("vec: {:?}", x);
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the linked rustc ticket and the examples in this issue to understand the conditional push pattern and intended suggestion. Identify the Clippy lint entry points and relevant test location in the repository. Done means the lint recognizes the pattern and suggests conditional Vec::with_capacity() without changing the resulting elements.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
performance, tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.