Skip to content

Instantly share code, notes, and snippets.

@herval
Created September 25, 2012 21:45
Show Gist options
  • Save herval/3784658 to your computer and use it in GitHub Desktop.
Save herval/3784658 to your computer and use it in GitHub Desktop.
Comparing each, Hash[] and inject performance
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment