Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
anp opened this issue Dec 4, 2024 · 0 comments
Labels
C-bug Category: Clippy is not doing the correct thing

Comments

@anp
Copy link
Member

anp commented Dec 4, 2024

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

@anp anp added the C-bug Category: Clippy is not doing the correct thing label Dec 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing
Projects
None yet
Development

No branches or pull requests

1 participant