除了其他答案之外,我将添加如果您能够构建Hash
using symbols
,因为keys
您performance
在收集值时可以获得收益,例如:
require 'benchmark'
members_without_sym = {"total"=>3, "data"=>[
{"email"=>"foo@example.org", "timestamp"=>"2013-03-16 01:11:01"},
{"email"=>"bar@example.org", "timestamp"=>"2013-03-16 02:07:30"},
{"email"=>"exx@example.org", "timestamp"=>"2013-03-16 03:06:24"}
]}
members_with_sym = {:total=>3, :data=>[
{:email=> "foo@example.org", :timestamp => "2013-03-16 01:11:01"},
{:email=> "bar@example.org", :timestamp => "2013-03-16 02:07:30"},
{:email=> "exx@example.org", :timestamp=> "2013-03-16 03:06:24"}
]}
Benchmark.bm(1) do |algo|
algo.report("Without symbol"){
2_000_000.times do
members_without_sym['data'].collect { |h| h['email'] }
end
}
algo.report("With symbol"){
2_000_000.times do
members_with_sym[:data].collect { |h| h[:email] }
end
}
end
结果:
user system total real
Without symbol 2.260000 0.000000 2.260000 ( 2.254277)
With symbol 0.880000 0.000000 0.880000 ( 0.878603)