@@ -20,6 +20,20 @@ declare_clippy_lint! {
20
20
/// These structures are non-idiomatic and less efficient than simply using
21
21
/// `vec![0; len]`.
22
22
///
23
+ /// More specifically, for `vec![0; len]`, the compiler can use a more specialized type of allocation
24
+ /// that also zero-initializes the allocated memory in the same call
25
+ /// (see: [alloc_zeroed](https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html#method.alloc_zeroed)).
26
+ ///
27
+ /// Writing `Vec::new()` followed by `vec.resize(len, 0)` is suboptimal because,
28
+ /// while it does do the same number of allocations,
29
+ /// it involves two operations for allocating and initializing.
30
+ /// The `resize` call first allocates memory (since `Vec::new()` did not), and only *then* zero-initializes it.
31
+ ///
32
+ /// Writing `Vec::with_capacity(size)` followed by `vec.resize(len, 0)` is similar.
33
+ /// The allocation shifts from `resize` to `with_capacity`,
34
+ /// but the zero-initialization still happens separately,
35
+ /// when it could be done in one call with `vec![0; len]` (`alloc_zeroed`).
36
+ ///
23
37
/// ### Example
24
38
/// ```rust
25
39
/// # use core::iter::repeat;
@@ -32,13 +46,17 @@ declare_clippy_lint! {
32
46
///
33
47
/// let mut vec2 = Vec::with_capacity(len);
34
48
/// vec2.extend(repeat(0).take(len));
49
+ ///
50
+ /// let mut vec3 = Vec::new();
51
+ /// vec3.resize(len, 0);
35
52
/// ```
36
53
///
37
54
/// Use instead:
38
55
/// ```rust
39
56
/// # let len = 4;
40
57
/// let mut vec1 = vec![0; len];
41
58
/// let mut vec2 = vec![0; len];
59
+ /// let mut vec3 = vec![0; len];
42
60
/// ```
43
61
#[ clippy:: version = "1.32.0" ]
44
62
pub SLOW_VECTOR_INITIALIZATION ,
0 commit comments