Merge pull request #21017 from alexheretic/faster-inline-clones

Optimise `SmolStr::clone` 4-5x speedup inline, 0.5x heap (slow down)
This commit is contained in:
Chayim Refael Friedman 2025-11-23 10:57:38 +00:00 committed by GitHub
commit 813c7d43db
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 4 deletions

View File

@ -1,6 +1,7 @@
# Changelog
## Unreleased
- Optimise `SmolStr::clone` 4-5x speedup inline, 0.5x heap (slow down).
## 0.3.4 - 2025-10-23

View File

@ -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) }
}
}