Unnamed repository; edit this file 'description' to name the repository.
Merge pull request #21017 from alexheretic/faster-inline-clones
Optimise `SmolStr::clone` 4-5x speedup inline, 0.5x heap (slow down)
Chayim Refael Friedman 5 months ago
parent 8c978e3 · parent d52491b · commit 813c7d4
-rw-r--r--lib/smol_str/CHANGELOG.md1
-rw-r--r--lib/smol_str/src/lib.rs16
2 files changed, 13 insertions, 4 deletions
diff --git a/lib/smol_str/CHANGELOG.md b/lib/smol_str/CHANGELOG.md
index fb65d88ad1..b7da6d18a4 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 31695b8117..582ea2e1fd 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) }
}
}