Last active
June 18, 2020 14:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Thanks for the JRuby version! Interesting! That's cool for
Hash[map]
because it's my favorite version along with thezip
FP-style pipeline. Also interesting that in JRubyreduce
seems slower thaneach_with_object
, whereas in MRI they are close and in MRI 2.3.0 they seem to be exactly the same.