rust-analyzer icon indicating copy to clipboard operation
rust-analyzer copied to clipboard

SmolStrBuilder: move rather than alloc + copy on finish

Open cerdelen opened this issue 1 month ago • 2 comments

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 (https://github.com/rust-analyzer/smol_str/issues/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.

cerdelen avatar Dec 02 '25 19:12 cerdelen

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 https://github.com/rust-analyzer/smol_str/issues/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.

alexheretic avatar Dec 02 '25 20:12 alexheretic

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

ChayimFriedman2 avatar Dec 02 '25 20:12 ChayimFriedman2