Skip to content

Commit

Permalink
Add PartialEq shortcut for ptr_eq strings
Browse files Browse the repository at this point in the history
This first compares the `Repr` before falling back to actually comparing the raw `as_str` itself.
In some micro-benchmarks, this speeds up inline and heap string comparisons when equal by ~70%.

There is a tiny hit in the non-equal case however. It is also noteworthy that the assembly generated for `Repr` is horrible,
and looks like its above the inlining threshold now.
  • Loading branch information
Swatinem authored and Veykril committed Feb 8, 2024
1 parent 0078fdf commit 9971a3f
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ impl Deref for SmolStr {

impl PartialEq<SmolStr> for SmolStr {
fn eq(&self, other: &SmolStr) -> bool {
self.as_str() == other.as_str()
self.0.ptr_eq(&other.0) || self.as_str() == other.as_str()
}
}

Expand Down Expand Up @@ -424,7 +424,7 @@ const _: () = {
assert!(WS.as_bytes()[N_NEWLINES] == b' ');
};

#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
enum InlineSize {
_V0 = 0,
Expand Down Expand Up @@ -536,6 +536,24 @@ impl Repr {
}
}
}

fn ptr_eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Heap(l0), Self::Heap(r0)) => Arc::ptr_eq(l0, r0),
(Self::Static(l0), Self::Static(r0)) => core::ptr::eq(l0, r0),
(
Self::Inline {
len: l_len,
buf: l_buf,
},
Self::Inline {
len: r_len,
buf: r_buf,
},
) => l_len == r_len && l_buf == r_buf,
_ => false,
}
}
}

/// Convert value to [`SmolStr`] using [`fmt::Display`], potentially without allocating.
Expand Down

0 comments on commit 9971a3f

Please sign in to comment.