-
Notifications
You must be signed in to change notification settings - Fork 377
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
Enumerable#sort_by is not always faster than #sort #120
Comments
In your sample you sort the |
I don't follow. ARRAY is not mutated. If you call I get the same results when I change the order of the samples:
|
The code example in this repo also does the same thing: it defines the array to be used in the samples as a constant: https://github.com/JuanitoFatas/fast-ruby/blob/master/code/enumerable/sort-vs-sort_by.rb |
@monfresh Thanks for pointing this out. There are two ways to resolve into the current example,
@JuanitoFatas Any comments about above? |
@monfresh Sorry - I used in my local sample |
I just ran into a situation where require 'benchmark/ips'
records = SomeModel.group(:some_column).sum(:value)
Benchmark.ips do |x|
x.report("with #sort") do |n|
n.times { records.sort { |x, y| y[1] <=> x[1] } }
end
x.report("with #sort_by") do |n|
n.times { records.sort_by(&:last) }
end
# Compare the iterations per second of the various reports!
x.compare!
end Yields
This is with 2 items in the result. When I bump this to 100:
Apparently there is a correlation between the number of items and the performance difference, which makes sense of course. Adding items to the array brings us closer to the 'true' performance difference between So lets bump to 1000:
So at 1000 items I don't know how we'd go about this, but adding a note about the expected number of items in the array would make sense. |
🙏 |
Per the Ruby 2.4.0 docs:
Here's a concrete example showing
sort
to be 2.70x faster in Ruby 1.9.3, 2.3.3 and 2.4.0:The text was updated successfully, but these errors were encountered: