People often ask what is the best way to sort a hash, but then they don\'t ask the needed follow-up question about what is the fastest way, which really determ
Here are some more interesting things to consider:
require 'fruity'
puts "Running Ruby v#{ RUBY_VERSION }"
# >> Running Ruby v2.2.2
require 'fruity'
puts "Running Ruby v#{ RUBY_VERSION }"
# >> Running Ruby v2.2.2
This looks at the differences using an integer as a key:
HASH = Hash[[*(1..100)].shuffle.map{ |k| [k, 1] }]
compare do
_sort1 { HASH.sort.to_h }
_sort2 { HASH.sort{ |a, b| a[0] <=> b[0] }.to_h }
_sort3 { HASH.sort{ |a, b| a.first <=> b.first }.to_h }
_sort_by { HASH.sort_by{ |k,v| k }.to_h }
end
# >> Running each test 64 times. Test will take about 1 second.
# >> _sort_by is faster than _sort2 by 70.0% ± 1.0%
# >> _sort2 is faster than _sort3 by 19.999999999999996% ± 1.0%
# >> _sort3 is faster than _sort1 by 19.999999999999996% ± 1.0%
This looks at the differences using a single-character string as the key:
HASH = Hash[[*('a'..'Z')].shuffle.map{ |k| [k, 1] }]
compare do
_sort1 { HASH.sort.to_h }
_sort2 { HASH.sort{ |a, b| a[0] <=> b[0] }.to_h }
_sort3 { HASH.sort{ |a, b| a.first <=> b.first }.to_h }
_sort_by { HASH.sort_by{ |k,v| k }.to_h }
end
# >> Running each test 16384 times. Test will take about 1 second.
# >> _sort1 is similar to _sort3
# >> _sort3 is similar to _sort2
# >> _sort2 is faster than _sort_by by 1.9x ± 0.1