From c283eabf66c575c3d1a9e56576cfe4c1a91aa136 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Mon, 2 Dec 2024 11:16:04 +0100 Subject: [PATCH] Optimize `String#==` taking character size into account (#15233) Co-authored-by: Oleh Prypin --- src/string.cr | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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