mirror of
https://github.com/rust-lang/rust-clippy
synced 2024-11-23 21:23:56 +00:00
clarify why Vec::new()
+ resize is worse than vec![0; N]
This commit is contained in:
parent
7c595b4599
commit
830bac5548
1 changed files with 18 additions and 0 deletions
|
@ -20,6 +20,20 @@ declare_clippy_lint! {
|
|||
/// 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 @@ declare_clippy_lint! {
|
|||
///
|
||||
/// 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 @@ declare_clippy_lint! {
|
|||
/// # 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,
|
||||
|
|
Loading…
Reference in a new issue