public
Created

Comparing each, Hash[] and inject performance

  • Download Gist
each_hash_inject.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
require 'benchmark'
 
runs = 1000
 
original_data = {}
1000.times do |t| # 1000 depts with 100 guys each
original_data["dept_#{t}"] = (1..100).to_a
end
 
def employee_name(id)
id.to_s
end
 
Benchmark.bm do|b|
b.report("each") do
runs.times do
new_data = {}
original_data.each { |dept, employee_ids| new_data[dept] = employee_ids.collect{ |id| employee_name(id) } }
end
end
 
b.report("Hash[]") do
runs.times do
new_data = Hash[ original_data.collect{ |dept, employee_ids| [dept, employee_ids.collect{ |id| employee_name(id) }] } ]
end
end
 
b.report("inject") do
runs.times do
new_data = original_data.inject({}) { |new_hash, dept_and_ids| new_hash[dept_and_ids[0]] = dept_and_ids[1].collect{ |id| employee_name(id) }; new_hash; }
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.