-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Optimise Indexable#== #4045
Optimise Indexable#== #4045
Conversation
We shouldn't have Any benchmark to show the actual improvement? |
I just did a benchmark for this and it seems a tad bit faster (based on 5 runs) require "benchmark"
a = [1, 2]
b = [1, 2]
Benchmark.ips do |x|
x.report("Equals") do
a.equals?(b) { |x, y| x == y }
end
end With 0.25.0
With PR
|
We can't assume other is an Indexable, just that it has size and []. |
@asterite I see what you mean, then this isn't any good as I guess one alternative would be to overload. Would you recommend that? I'm pretty new here...can you explain why it's safe to assume |
FWIW, the performance gains are more significant with a larger array.
0.25.0
PR
|
@karlseguin For example if I have this: class MyIndexable
getter size
def initialize(@size : Int32)
end
def [](index)
if 0 <= index < @size
index
else
raise IndexError.new
end
end
end
a = [0, 1, 2]
b = MyIndexable.new(3)
p a.equals?(b) { |x, y| x == y } It's a super hypothetical case, though. What we can do is to overload |
src/indexable.cr
Outdated
@@ -211,6 +211,16 @@ module Indexable(T) | |||
size == 0 | |||
end | |||
|
|||
# Optimized version of `Indexable#equals?` used when `other` is also an | |||
# `Indexable`. | |||
def equals?(other : Indexable(T)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's no need to restrict against T
, just Indexable
is good.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, didn't know. Thanks.
Do you know how to get the docs to link to the correct overload? Couldn't figure it out.
other's value through unsafe_at as its size has already been checked.
@karlseguin Thank you for this! 💚 |
Use
unsafe_at
on other as the size has already been checked.