Skip to content

slow-vector-initialization should catch Vec::new followed by Vec::resize(len, 0). #10938

Closed
@JarredAllen

Description

@JarredAllen

Summary

There's a lint, slow-vector-initialization, which catches if you try to do something like this:

let mut foo = Vec::with_capacity(1024);
foo.resize(1024, 0);

It suggests you use the vec! macro instead, which is faster. However, if you replace the call to Vec::with_capacity with Vec::new, you get an even worse-performing version of the same code, and clippy is no longer able to suggest the better option.

Lint Name

slow-vector-initialization

Reproducer

I tried this code:

pub fn main() {
    let mut bar = Vec::new();
    bar.resize(1024, 0);
}

I expected to see this happen:

Raise an instance of slow-vector-initialization, something similar to this:

warning: slow zero-filling initialization
 --> src/main.rs:3:5
  |
2 |     let mut bar = Vec::new();
  |                   ------------------ help: consider replace allocation with: `vec![0; 1024]`
3 |     bar.resize(1024, 0);
  |     ^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#slow_vector_initialization
  = note: `#[warn(clippy::slow_vector_initialization)]` on by default

Instead, this happened:

No lint raised

Version

rustc 1.70.0 (90c541806 2023-05-31)
binary: rustc
commit-hash: 90c541806f23a127002de5b4038be731ba1458ca
commit-date: 2023-05-31
host: aarch64-apple-darwin
release: 1.70.0
LLVM version: 16.0.2

(this also happens on the version running on playground right now)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-negativeIssue: The lint should have been triggered on code, but wasn't

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions