Skip to content

Instantly share code, notes, and snippets.

@jonatack
Last active June 18, 2020 14:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonatack/b382c2a806d553ce8d57 to your computer and use it in GitHub Desktop.
Save jonatack/b382c2a806d553ce8d57 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
@jonatack
Copy link
Author

Thanks for the JRuby version! Interesting! That's cool for Hash[map] because it's my favorite version along with the zip FP-style pipeline. Also interesting that in JRuby reduce seems slower than each_with_object, whereas in MRI they are close and in MRI 2.3.0 they seem to be exactly the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment