From 830bac554898fa6e3969876134324df4b41670c1 Mon Sep 17 00:00:00 2001 From: y21 <30553356+y21@users.noreply.github.com> Date: Wed, 9 Aug 2023 14:00:06 +0200 Subject: [PATCH] clarify why `Vec::new()` + resize is worse than `vec![0; N]` --- clippy_lints/src/slow_vector_initialization.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/clippy_lints/src/slow_vector_initialization.rs b/clippy_lints/src/slow_vector_initialization.rs index 54a33eb2986..2117bcae22c 100644 --- a/clippy_lints/src/slow_vector_initialization.rs +++ b/clippy_lints/src/slow_vector_initialization.rs @@ -20,6 +20,20 @@ /// These structures are non-idiomatic and less efficient than simply using /// `vec![0; len]`. /// + /// More specifically, for `vec![0; len]`, the compiler can use a more 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. + /// + /// Writing `Vec::with_capacity(size)` followed by `vec.resize(len, 0)` is similar. + /// The allocation shifts from `resize` to `with_capacity`, + /// but the zero-initialization still happens separately, + /// when it could be done in one call with `vec![0; len]` (`alloc_zeroed`). + /// /// ### Example /// ```rust /// # use core::iter::repeat; @@ -32,6 +46,9 @@ /// /// let mut vec2 = Vec::with_capacity(len); /// vec2.extend(repeat(0).take(len)); + /// + /// let mut vec3 = Vec::new(); + /// vec3.resize(len, 0); /// ``` /// /// Use instead: @@ -39,6 +56,7 @@ /// # 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,