对某些给出的答案做了一些快速,肮脏的基准测试。(这些发现可能与基于Ruby版本,奇怪的缓存等的发现并不完全相同,但是总体结果将是相似的。)
arr
是ActiveRecord对象的集合。
Benchmark.measure {
100000.times {
Hash[arr.map{ |a| [a.id, a] }]
}
}
基准@ real = 0.860651,@ cstime = 0.0,@ cutime = 0.0,@ stime = 0.0,@ utime = 0.8500000000000005,@ total = 0.8500000000000005
Benchmark.measure {
100000.times {
h = Hash[arr.collect { |v| [v.id, v] }]
}
}
基准@ real = 0.74612,@ cstime = 0.0,@ cutime = 0.0,@ stime = 0.010000000000000009,@ utime = 0.740000000000002,@ total = 0.750000000000002
Benchmark.measure {
100000.times {
hash = {}
arr.each { |a| hash[a.id] = a }
}
}
基准@ real = 0.627355,@ cstime = 0.0,@ cutime = 0.0,@ stime = 0.010000000000000009,@ utime = 0.6199999999999974,@ total = 0.6299999999999975
Benchmark.measure {
100000.times {
arr.each_with_object({}) { |v, h| h[v.id] = v }
}
}
基准@ real = 1.650568,@ cstime = 0.0,@ cutime = 0.0,@ stime = 0.12999999999999998,@ utime = 1.51,@ total = 1.64
结论
仅仅因为Ruby具有表现力和动态性,并不意味着您应该始终寻求最漂亮的解决方案。基本的每个循环在创建哈希中最快。
... { |v| [v, f(v)] }
,但这确实成功了!