From 45256520e1b076fdfb8c32be38c77b88f5bbeb74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Wed, 27 Nov 2024 12:06:05 +0100 Subject: [PATCH] Optimize `Slice#<=>` and `#==` with reference check --- src/slice.cr | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/slice.cr b/src/slice.cr index ace008e53e05..266d7bb31249 100644 --- a/src/slice.cr +++ b/src/slice.cr @@ -825,6 +825,9 @@ struct Slice(T) # Bytes[1, 2] <=> Bytes[1, 2] # => 0 # ``` def <=>(other : Slice(U)) forall U + # If both slices are identical references, we can skip the memory comparison. + return 0 if same?(other) + min_size = Math.min(size, other.size) {% if T == UInt8 && U == UInt8 %} cmp = to_unsafe.memcmp(other.to_unsafe, min_size) @@ -847,8 +850,13 @@ struct Slice(T) # Bytes[1, 2] == Bytes[1, 2, 3] # => false # ``` def ==(other : Slice(U)) : Bool forall U + # If both slices are of different sizes, they cannot be equal. return false if size != other.size + # If both slices are identical references, we can skip the memory comparison. + # Not using `same?` here because we have already compared sizes. + return true if to_unsafe == other.to_unsafe + {% if T == UInt8 && U == UInt8 %} to_unsafe.memcmp(other.to_unsafe, size) == 0 {% else %}