Skip to content

Conversation

@cerdelen
Copy link

@cerdelen cerdelen commented Dec 2, 2025

Removing unnessecary len checks as well as 1 redundant alloc + copy on finishing a Builder into a SmolStr.

Browsing the old repo for smolstr i came about an issue that mentioned a redundant alloc + copy when finishing a SmolStrBuilder (rust-analyzer/smol_str#94) by @alexheretic.

The solution passes all tests and skips the conditional tests in the Repr::new(), and as long as the internal String has not too much unused capacity the will skip a reallocation + copy. (into_boxed_str() uses shrink_to_fit)

NOTE: It does change the finish function signature. finish() took a &self so far. This is contrary to what a user would understand from the word finish, imo.

Someone with merging power needs to decide if this change of signature is acceptable.

Removing unnessecary len checks as well as 1 redundant alloc + copy on
finishing a Builder into a SmolStr
@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Dec 2, 2025
@alexheretic
Copy link
Contributor

I think i tried this and couldn't produce a benchmark improvement. Do you see better perf with this, e.g. with the format benchmark?

Btw this doesn't solve rust-analyzer/smol_str#94 as, iirc that was about the String -> Arc extra allocation.

But such an optimisation does make some sense, though I doubt it's worth making a breaking api change for it. A new method + deprecation could avoid this.

}
}
SmolStrBuilderRepr::Heap(heap) => Repr::new(heap),
SmolStrBuilderRepr::Heap(heap) => Repr::Heap(Arc::from(heap.into_boxed_str())),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will allocate more, not less. Arc::from will allocate anyway, so this just has the extra allocation for into_boxed_str().

@ChayimFriedman2
Copy link
Contributor

As explained in the comment there isn't any actual optimization done here, therefore this is definitely not worth the API breakage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants