Skip to content

[slow_vector_initialization]: clarify why Vec::new() + resize is worse #11310

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

Merged
merged 3 commits into from
Aug 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions clippy_lints/src/slow_vector_initialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,35 @@ declare_clippy_lint! {
/// These structures are non-idiomatic and less efficient than simply using
/// `vec![0; len]`.
///
/// Specifically, for `vec![0; len]`, the compiler can use a specialized type of allocation
/// that also zero-initializes the allocated memory in the same call
/// (see: [alloc_zeroed](https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html#method.alloc_zeroed)).
///
/// Writing `Vec::new()` followed by `vec.resize(len, 0)` is suboptimal because,
/// while it does do the same number of allocations,
/// it involves two operations for allocating and initializing.
/// The `resize` call first allocates memory (since `Vec::new()` did not), and only *then* zero-initializes it.
///
/// ### Example
/// ```rust
/// # use core::iter::repeat;
/// # let len = 4;
/// let mut vec1 = Vec::with_capacity(len);
/// let mut vec1 = Vec::new();
/// vec1.resize(len, 0);
///
/// let mut vec1 = Vec::with_capacity(len);
/// vec1.resize(vec1.capacity(), 0);
///
/// let mut vec2 = Vec::with_capacity(len);
/// vec2.extend(repeat(0).take(len));
/// vec2.resize(len, 0);
///
/// let mut vec3 = Vec::with_capacity(len);
/// vec3.extend(repeat(0).take(len));
/// ```
///
/// Use instead:
/// ```rust
/// # let len = 4;
/// let mut vec1 = vec![0; len];
/// let mut vec2 = vec![0; len];
/// let mut vec3 = vec![0; len];
/// ```
#[clippy::version = "1.32.0"]
pub SLOW_VECTOR_INITIALIZATION,
Expand Down