compact_str
compact_str copied to clipboard
Should From<String> convert to inline if possible?
I was profiling something and noticed that CompactString::clone
was hitting the allocator consistently even though the strings were small. Turns out that if you convert a String into CompactString using the From/Into trait it'll do so by taking ownership of the backing allocation as expected. But as a side-effect further clones will behave like String::clone even if the strings would fit inline.
If you are using CompactString chances are you expect it to be inlineable most of the time so this comes as a performance pitfall depending on how the CompactString was created.
I suggest changing From<String>
to convert to inline if possible to avoid this scenario. Doing so may make From<CompactString> for String
slower but I'll argue that an allocation is expected in this case and any re-use is a bonus. Alternatively the Clone implementation can check if the clone should be inline even if the source is boxed.
One could also argue for full flexibility and that the behavior should be kept and a new function added CompacString::compact
, but it's both cumbersome to use and most people will never realize it's thing. If such hyperspecific apis are desirable I suggest a different constructor that keeps the exiting behavior CompactString::from_string_buffer
.