Skip to content

Commit

Permalink
Optimize String#== taking character size into account
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Nov 27, 2024
1 parent b87d3e8 commit 907581b
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions 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)

# If the bytesize differs, they cannot be equal
return false unless 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 unless (@length == other.@length) || (@length & other.@length).zero?

# 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 907581b

Please sign in to comment.