Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Slice#<=> and #== with reference check #15234

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading