我有一个非常大的散列,我想迭代它。 Hash.each
似乎太慢了。
有什么有效的方法可以做到这一点吗?
如何将这个散列转换为数组?
在每个循环中,我都在做非常简单的字符串操作:
name_hash.each {|name, str|
record += name.to_s + "\|" + str +"\n"
}
并且散列以人名为键,一些相关内容为值:
name_hash = {:"jose garcia" => "ca:tw#2@1,2@:th#1@3@;ar:tw#1@4@:fi#1@5@;ny:tw#1@6@;"}
最佳答案
考虑以下示例,它使用了 100 万个元素的散列:
#! /usr/bin/env ruby
require 'benchmark'
h = {}
1_000_000.times do |n|
h[n] = rand
end
puts Benchmark.measure { h.each { |k, v| } }
a = nil
puts Benchmark.measure { a = h.to_a }
puts Benchmark.measure { a.each { |k, v| } }
我在工作时在我的系统上运行它(运行 Ruby 1.8.5),我得到:
0.350000 0.020000 0.370000 ( 0.380571)
0.300000 0.020000 0.320000 ( 0.307207)
0.160000 0.040000 0.200000 ( 0.198388)
因此遍历数组确实更快(0.16 秒对散列的 0.35 秒)。但是生成数组需要0.3秒。因此,净过程比 0.35 秒慢了 0.46 秒。
所以看起来最好只迭代散列,至少在这个测试用例中是这样。
关于ruby-on-rails - ruby:如何有效地迭代哈希中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11978421/