Skip to content

Commit

Permalink
Optimize String#== taking character size into account (#15233)
Browse files Browse the repository at this point in the history
Co-authored-by: Oleh Prypin <[email protected]>
  • Loading branch information
straight-shoota and oprypin authored Dec 2, 2024
1 parent 8e339d1 commit c283eab
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3088,8 +3088,18 @@ class String
# "abcdef".compare("ABCDEF", case_insensitive: true) == 0 # => true
# ```
def ==(other : self) : Bool
# Quick pointer comparison if both strings are identical references
return true if same?(other)
return false unless bytesize == other.bytesize

# If the bytesize differs, they cannot be equal
return false if bytesize != other.bytesize

# If the character size of both strings differs, they cannot be equal.
# We need to exclude the case that @length of either string might not have
# been calculated (indicated by `0`).
return false if @length != other.@length && @length != 0 && other.@length != 0

# All meta data matches up, so we need to compare byte-by-byte.
to_unsafe.memcmp(other.to_unsafe, bytesize) == 0
end

Expand Down

0 comments on commit c283eab

Please sign in to comment.