对哈希进行排序的最快方法是什么? [英] What is the fastest way to sort a Hash?

查看:47
本文介绍了对哈希进行排序的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们经常问什么是最好的散列排序方式,但随后他们不会问所需的后续问题,关于什么是最快方式,这确实决定了最佳方式.

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 determines the best way.

在 Ruby 中对 Hash 进行排序的最快方法是什么,而不管所使用的 Ruby 版本如何?

What is the fastest way to sort a Hash in Ruby, regardless of the version of Ruby being used?

我正在寻找其他答案,以涵盖极端情况,或者用更通用和/或最快的方法发现问题.

I'm looking for additional answers that will cover corner cases, or uncover problems with the more generic and/or fastest methods.

推荐答案

对 Hash 进行排序的最快方法是什么?

What is the fastest way to sort a Hash?

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 the above code on a Mac OS laptop results in the following output:

# >> 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

还有:

# >> 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

<小时>

将哈希大小加倍:


Doubling the hash size:

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

还有:

# >> 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

<小时>

这些值会因硬件而异,但相对结果不应改变.


The values will change depending on the hardware, but the relative results shouldn't change.

Fruity 被选择使用内置的 基准 类为简单起见.

Fruity was chosen over using the built-in Benchmark class for simplicity.

这是由按键排序哈希,在 Ruby 中返回哈希"提示的.

这篇关于对哈希进行排序的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆