Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lbvf50mobile/3b72ce448a52f6b9746fcc226a49093d to your computer and use it in GitHub Desktop.
Save lbvf50mobile/3b72ce448a52f6b9746fcc226a49093d to your computer and use it in GitHub Desktop.
Benchmark building a Ruby hash: #each - #each_with_object - #reduce - Hash[map] - #map.zip(map).to_h - #reduce-merge
require 'benchmark/ips'
Benchmark.ips do |x|
Property = Struct.new(:name, :original_name)
PROPERTIES = [
Property.new("Clo", "Chloe" ),
Property.new("Jon", "Jonathan" ),
Property.new("Kris", "Kristin" ),
Property.new("Dave", "David" ),
Property.new("Ana", "Anastasia" ),
Property.new("Mike", "Michael" ),
Property.new("Becky", "Rebecca" ),
Property.new("Will", "William" )
]
x.report('#each') do |times|
i = 0
while i < times
out = {}
PROPERTIES.each do |property|
out[property.name] = property.original_name
end
out
i += 1
end
end
x.report('#each_with_object') do |times|
i = 0
while i < times
PROPERTIES.each_with_object({}) do |property, memo|
memo[property.name] = property.original_name
end
i += 1
end
end
x.report('#reduce') do |times|
i = 0
while i < times
PROPERTIES.reduce({}) do |memo, property|
memo[property.name] = property.original_name
memo
end
i += 1
end
end
x.report('Hash[map]') do |times|
i = 0
while i < times
Hash[PROPERTIES.map { |property| [property.name, property.original_name] }]
i += 1
end
end
x.report('#map.zip(map).to_h') do |times|
i = 0
while i < times
PROPERTIES.map(&:name).zip(PROPERTIES.map(&:original_name)).to_h
i += 1
end
end
x.report('#reduce-merge') do |times|
i = 0
while i < times
PROPERTIES.reduce({}) { |memo, property| memo.merge(property.name => property.original_name) }
i += 1
end
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment