Skip to content

slow_vector_initialization should recommend removing Vec::resize() calls in addition to adding the size to the macro #13781

@anp

Description

@anp

Summary

slow_vector_initialization is very useful, but its suggestion when handling an empty vec![] followed by a call to Vec::resize() does not recommend removing the call to Vec::resize(). This oversight will typically be caught in code review but when fixing many places the lint is triggered it might be missed.

When missed, the resize call will typically not be a very big hit to performance because it won't allocate, but there are some cases where the suggestion guides users to copy a complicated expression from resize to the macro invocation. One hopes that the optimizer would be able to deduplicate the resulting calls but they might have side effects or be missed when optimizing for other reasons.

Reproducer

I tried this code:

#![warn(clippy::slow_vector_initialization)]
fn main() {
    let mut v = vec![];
    v.resize(10, 0);
}

I expected to see this happen: a suggestion that replaces the vec![] call with vec![0; 10] and suggests removing the call to v.resize(10, 0);

Instead, this happened:

warning: slow zero-filling initialization
 --> src/main.rs:4:5
  |
3 |     let mut v = vec![];
  |                 ------ help: consider replacing this with: `vec![0; 10]`
4 |     v.resize(10, 0);
  |     ^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#slow_vector_initialization
note: the lint level is defined here
 --> src/main.rs:1:9
  |
1 | #![warn(clippy::slow_vector_initialization)]
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

playground

Version

clippy 0.1.83 (2024-11-26 90b35a6) from the playground

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions