gpui: Avoid copying and comparing the bytes of shared text (#66728)

Two small changes that avoid touching the bytes of text that hasn't
changed:

- `SharedString` equality checks whether both sides point at the same
bytes before comparing them. `SmolStr` compares heap-allocated and
static strings byte by byte even when both are clones of the same
allocation, which is common when a view clones the same label into its
elements every frame. Strings of up to 23 bytes are stored inline and
still use `SmolStr`'s comparison. `Hash` is now implemented by hand
(clippy rejects deriving it alongside a manual `PartialEq`) and hashes
exactly as before.
- A `&'static str` text child (e.g. `div().child("Some label")`) is
wrapped with `SharedString::new_static` instead of copied every frame,
which allocated for strings longer than 23 bytes. Its comparisons now
hit the pointer check above.

Release Notes:

- N/A
- [GPUI] Avoid allocating for a SharedString in `imp Element for
&'static str`
This commit is contained in:
Anthony Eid
2026-11-10 23:00:03 +00:00
committed by GitHub
parent 0d1756eb10
commit 415d310e52
2 changed files with 15 additions and 2 deletions
+1 -1
View File
@@ -263,7 +263,7 @@ impl Element for &'static str {
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
let state = TextLayout::default();
let layout_id = state.layout(SharedString::from(*self), None, window, cx);
let layout_id = state.layout(SharedString::new_static(self), None, window, cx);
(layout_id, state)
}
@@ -11,9 +11,22 @@ use smol_str::SmolStr;
/// A shared string is an immutable string that can be cheaply cloned in GPUI
/// tasks. Essentially an abstraction over an `Arc<str>` and `&'static str`,
/// currently backed by a [`SmolStr`].
#[derive(Eq, PartialEq, PartialOrd, Ord, Hash, Clone)]
#[derive(Eq, PartialOrd, Ord, Clone)]
pub struct SharedString(SmolStr);
impl PartialEq for SharedString {
fn eq(&self, other: &Self) -> bool {
let (this, other_str) = (self.as_str(), other.as_str());
(this.as_ptr() == other_str.as_ptr() && this.len() == other_str.len()) || self.0 == other.0
}
}
impl std::hash::Hash for SharedString {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl std::ops::Deref for SharedString {
type Target = str;