Skip to content

Instantly share code, notes, and snippets.

@anga
Created December 16, 2020 16:30
Show Gist options
  • Save anga/3df46fb4381a715bb9c6aeb99a8cf421 to your computer and use it in GitHub Desktop.
Save anga/3df46fb4381a715bb9c6aeb99a8cf421 to your computer and use it in GitHub Desktop.
Merging Hases in Ruby 2.7.1p83
require 'benchmark'
a = {foo: 'Hello'}
b = {bar: ' world'}
n = 100_000_000
Benchmark.bm do |x|
x.report("{**a,**b}") do
n.times {
{**a, **b}
}
end
x.report("{}.merge(a,b)") do
n.times {
{}.merge(a,b)
}
end
x.report("{}.merge(**a,**b)") do
n.times {
{}.merge(**a,**b)
}
end
x.report("{}.merge!(a,b)") do
n.times {
{}.merge!(a,b)
}
end
x.report("{}.update(a,b)") do
n.times {
{}.update(a,b)
}
end
x.report("[*a,*b].to_h") do
n.times {
[*a,*b].to_h
}
end
end
# Results
# {**a,**b} 18.499090 0.000953 18.500043 ( 18.535218)
# {}.merge(a,b) 17.367425 0.000000 17.367425 ( 17.396814)
# {}.merge(**a,**b) 31.909342 0.000000 31.909342 ( 31.962684)
# {}.merge!(a,b) 14.842274 0.000000 14.842274 ( 14.867258)
# {}.update(a,b) 14.798517 0.000000 14.798517 ( 14.821953)
# [*a,*b].to_h 52.512334 0.000000 52.512334 ( 52.600762)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment