Skip to content

Commit

Permalink
Optimize Slice#<=> and #== with reference check
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Nov 27, 2024
1 parent b87d3e8 commit 4525652
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/slice.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 %}
Expand Down

0 comments on commit 4525652

Please sign in to comment.