Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.