对哈希进行排序的最快方法是什么?
require 'fruity'
HASH = Hash[('a'..'z').to_a.shuffle.map{ |k| [k, 1] }]
def sort_hash1(h)
h.sort.to_h
end
def sort_hash2(h)
Hash[h.sort]
end
def sort_hash3(h)
Hash[h.sort_by{ |k, v| k }]
end
def sort_keys(h)
keys = h.keys.sort
Hash[keys.zip(h.values_at(*keys))]
end
puts "Running on Ruby v#{ RUBY_VERSION }"
puts
compare do
do_sort_hash1 { sort_hash1(HASH) } if [].respond_to?(:to_h)
do_sort_hash2 { sort_hash2(HASH) }
do_sort_hash3 { sort_hash3(HASH) }
do_sort_keys { sort_keys(HASH) }
end
在 Mac OS 笔记本电脑上运行上述代码会产生以下输出:
# >> Running on Ruby v2.2.2
# >>
# >> Running each test 256 times. Test will take about 1 second.
# >> do_sort_keys is faster than do_sort_hash3 by 39.99999999999999% ± 10.0%
# >> do_sort_hash3 is faster than do_sort_hash1 by 1.9x ± 0.1
# >> do_sort_hash1 is similar to do_sort_hash2
And:
# >> Running on Ruby v1.9.3
# >>
# >> Running each test 256 times. Test will take about 1 second.
# >> do_sort_keys is faster than do_sort_hash3 by 19.999999999999996% ± 10.0%
# >> do_sort_hash3 is faster than do_sort_hash2 by 4x ± 0.1
将哈希大小加倍:
HASH = Hash[[*('a'..'z'), *('A'..'Z')].shuffle.map{ |k| [k, 1] }]
结果是:
# >> Running on Ruby v2.2.2
# >>
# >> Running each test 128 times. Test will take about 1 second.
# >> do_sort_keys is faster than do_sort_hash3 by 50.0% ± 10.0%
# >> do_sort_hash3 is faster than do_sort_hash1 by 2.2x ± 0.1
# >> do_sort_hash1 is similar to do_sort_hash2
And:
# >> Running on Ruby v1.9.3
# >>
# >> Running each test 128 times. Test will take about 1 second.
# >> do_sort_keys is faster than do_sort_hash3 by 30.000000000000004% ± 10.0%
# >> do_sort_hash3 is faster than do_sort_hash2 by 4x ± 0.1
这些值将根据硬件而变化,但相对结果不应改变。
Fruity选择使用内置基准为了简单起见,类。
这是由“按键对哈希值进行排序,然后在 Ruby 中返回哈希值".