diff --git a/src/string.cr b/src/string.cr index 07d65f10dbd4..4b52d08c7426 100644 --- a/src/string.cr +++ b/src/string.cr @@ -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