Fix double allocation in push_str if the argument would promote from an Inline SmartString. #5
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi!
I found your project from https://fasterthanli.me/articles/small-strings-in-rust and thought it was awesome that there was a project for SSO!
I looked at the source code and thought I noticed a potential double allocation in the
push_str
method. I created a small project (copying the tracing allocator from the above blog post) to test my assumption and I think I'm right.It allocaties once to convert the
Inline
dSmartString
into aString
and again when it pushes the new&str
onto the end.I've created a small change that reserves the memory upfront so there is only a single allocation.
At the bottom of this post is the source code and Cargo.toml of the project that shows the double allocation.
This is the output I get when running
cargo run --release
with smartstring 0.2.2:And here is the output after applying this patch:
Note that
push
does not seem to benefit from this patch as it seemsStrings
seems to like to allocate 24 bytes, however it is no worse, so I made the change there for consistency.Never-the-less, in the
push_str
there is now only a single allocation.I appreciate this is a micro-optimisation, but as minimal allocations seems to be a goal for the project, I thought it was worthwhile.
Demo Project
Cargo.toml:
src/main.rs: