Skip to content

Commit d52491b

Browse files
committed
smol_str: Optimise inline SmolStr::clone
1 parent afcfe14 commit d52491b

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

lib/smol_str/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Changelog
22

33
## Unreleased
4+
- Optimise `SmolStr::clone` 4-5x speedup inline, 0.5x heap (slow down).
45

56
## 0.3.4 - 2025-10-23
67

lib/smol_str/src/lib.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,19 @@ impl SmolStr {
104104
impl Clone for SmolStr {
105105
#[inline]
106106
fn clone(&self) -> Self {
107-
if !self.is_heap_allocated() {
108-
// SAFETY: We verified that the payload of `Repr` is a POD
109-
return unsafe { core::ptr::read(self as *const SmolStr) };
107+
// hint for faster inline / slower heap clones
108+
#[cold]
109+
#[inline(never)]
110+
fn cold_clone(v: &SmolStr) -> SmolStr {
111+
SmolStr(v.0.clone())
110112
}
111-
Self(self.0.clone())
113+
114+
if self.is_heap_allocated() {
115+
return cold_clone(self);
116+
}
117+
118+
// SAFETY: We verified that the payload of `Repr` is a POD
119+
unsafe { core::ptr::read(self as *const SmolStr) }
112120
}
113121
}
114122

0 commit comments

Comments
 (0)