sort_by is the natural method to use here, but I was curious how it would compare with a method that sorted the values of the key :name and then used values_at to extract the hashes in the correct order (which requires that the array be first converted to a hash).
def sort_by_method(names_array)
names_array.sort_by { |hash| hash[:name] }
end
def values_at_method(names_array)
h = names_array.each_with_object({}) { |g,h| h[g[:name]] = g }
h.values_at *h.keys.sort
end
require 'fruity'
ALPHA = ('a'..'z').to_a
def bench_em(size, name_size)
names_array = size.times.map { { a: 1, name: ALPHA.sample(name_size).join, c: 2 } }
compare do
_sort_by { sort_by_method names_array }
_values_at { values_at_method names_array }
end
end
bench_em(100, 10)
Running each test 64 times. Test will take about 1 second.
_sort_by is similar to _values_at
bench_em(1_000, 10)
Running each test 4 times. Test will take about 1 second.
_values_at is similar to _sort_by
bench_em(10_000, 10)
Running each test once. Test will take about 1 second.
_sort_by is similar to _values_at
bench_em(100_000, 10)
Running each test once. Test will take about 8 seconds.
_sort_by is similar to _values_at
It appears performance is about the same, so sort_by, which is simpler and reads better, appears to be the best choice here.