From d52491b520128683e69949f045838ea0f69233d4 Mon Sep 17 00:00:00 2001 From: Alex Butler Date: Tue, 18 Nov 2025 11:41:54 +0000 Subject: [PATCH] smol_str: Optimise inline SmolStr::clone --- lib/smol_str/CHANGELOG.md | 1 + lib/smol_str/src/lib.rs | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/smol_str/CHANGELOG.md b/lib/smol_str/CHANGELOG.md index fb65d88ad191..b7da6d18a440 100644 --- a/lib/smol_str/CHANGELOG.md +++ b/lib/smol_str/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## Unreleased +- Optimise `SmolStr::clone` 4-5x speedup inline, 0.5x heap (slow down). ## 0.3.4 - 2025-10-23 diff --git a/lib/smol_str/src/lib.rs b/lib/smol_str/src/lib.rs index 31695b811747..582ea2e1fdb9 100644 --- a/lib/smol_str/src/lib.rs +++ b/lib/smol_str/src/lib.rs @@ -104,11 +104,19 @@ impl SmolStr { impl Clone for SmolStr { #[inline] fn clone(&self) -> Self { - if !self.is_heap_allocated() { - // SAFETY: We verified that the payload of `Repr` is a POD - return unsafe { core::ptr::read(self as *const SmolStr) }; + // hint for faster inline / slower heap clones + #[cold] + #[inline(never)] + fn cold_clone(v: &SmolStr) -> SmolStr { + SmolStr(v.0.clone()) } - Self(self.0.clone()) + + if self.is_heap_allocated() { + return cold_clone(self); + } + + // SAFETY: We verified that the payload of `Repr` is a POD + unsafe { core::ptr::read(self as *const SmolStr) } } }