-
Notifications
You must be signed in to change notification settings - Fork 1.6k
slow-vector-initialization
should catch Vec::new
followed by Vec::resize(len, 0)
.
#10938
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
Comments
Why aren't Or is it some special properly of |
I don't think so. Last I checked, |
It would be nice to get this explained more in https://rust-lang.github.io/rust-clippy/master/index.html#/slow_vect. Right now the only examples it gives are about initializations with |
Good point, this should be documented. I'll put up a PR for this in a bit |
…,djc [`slow_vector_initialization`]: clarify why `Vec::new()` + resize is worse #11198 extended this lint to also warn on `Vec::new()` + `resize(0, len)`, but did not update the lint documentation, so it left some confused (#10938 (comment)). This PR should make it a bit more clear. (cc `@djc` `@vi` what do you think about this?) <details> <summary>More details</summary> Godbolt for `Vec::new()` + `.resize(x, 0)`: https://godbolt.org/z/e7q9xc9rG The resize call first does a normal allocation (`__rust_alloc`): ```asm alloc::raw_vec::finish_grow: ... cmp qword ptr [rcx + 8], 0 je .LBB1_7 ; if capacity == 0 -> LBB1_7 .LBB1_7: ... call qword ptr [rip + __rust_alloc@GOTPCREL] ``` *Then* a memset for zero initialization: ```asm example::f: ... xor esi, esi ; 0 call qword ptr [rip + memset@GOTPCREL] ``` ------------ Godbolt for `vec![0; len]`: https://godbolt.org/z/M3vr53vWY Important bit: ```asm example::f: ... call qword ptr [rip + __rust_alloc_zeroed@GOTPCREL] ``` </details> changelog: [`slow_vector_initialization`]: clarify why `Vec::new()` + resize is worse than `vec![0; len]`
Summary
There's a lint,
slow-vector-initialization
, which catches if you try to do something like this:It suggests you use the
vec!
macro instead, which is faster. However, if you replace the call toVec::with_capacity
withVec::new
, you get an even worse-performing version of the same code, and clippy is no longer able to suggest the better option.Lint Name
slow-vector-initialization
Reproducer
I tried this code:
I expected to see this happen:
Raise an instance of
slow-vector-initialization
, something similar to this:Instead, this happened:
No lint raised
Version
The text was updated successfully, but these errors were encountered: