-
Notifications
You must be signed in to change notification settings - Fork 13.5k
Optimize Vec::shrink_to_fit() #21401
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
Conversation
This uses `Vec::shrink_to_fit()` internally so it's really benchmarking that.
`Vec::shrink_to_fit()` may be called on vectors that are already the correct length. Calling out to `reallocate()` in this case is a bad idea because there is no guarantee that `reallocate()` won't allocate a new buffer anyway, and based on performance seen in external benchmarks, it seems likely that it is in fact reallocating a new buffer. Before: test string::tests::bench_exact_size_shrink_to_fit ... bench: 45 ns/iter (+/- 2) After: test string::tests::bench_exact_size_shrink_to_fit ... bench: 26 ns/iter (+/- 1)
(rust_highfive has picked a reviewer for you, use r? to override) |
How does this impact code that actually needs to shrink? |
(I imagine the overhead is negligable if not free, but am still curious) |
@gankro I would imagine it's negligible too. It's a single comparison, of values that are already being used anyway so no cache faults or anything like that. I would welcome some actual profiling but I doubt I can get any meaningful measurements. |
Don't reallocate when capacity is already equal to length `Vec::shrink_to_fit()` may be called on vectors that are already the correct length. Calling out to `reallocate()` in this case is a bad idea because there is no guarantee that `reallocate()` won't allocate a new buffer anyway, and based on performance seen in external benchmarks, it seems likely that it is in fact reallocating a new buffer. Before: test string::tests::bench_exact_size_shrink_to_fit ... bench: 45 ns/iter (+/- 2) After: test string::tests::bench_exact_size_shrink_to_fit ... bench: 26 ns/iter (+/- 1)
Don't reallocate when capacity is already equal to length
Vec::shrink_to_fit()
may be called on vectors that are already thecorrect length. Calling out to
reallocate()
in this case is a bad ideabecause there is no guarantee that
reallocate()
won't allocate a newbuffer anyway, and based on performance seen in external benchmarks, it
seems likely that it is in fact reallocating a new buffer.
Before:
After: