Skip to content

Instantly share code, notes, and snippets.

@ryz310
Forked from kelan/test_merges.rb
Last active July 21, 2021 08:11
Show Gist options
  • Save ryz310/5db77d008124208e157e1e9bf8499776 to your computer and use it in GitHub Desktop.
Save ryz310/5db77d008124208e157e1e9bf8499776 to your computer and use it in GitHub Desktop.
Test ruby hash merging speed (#merge vs #merge!).
#!/usr/bin/env ruby
# To test is using `defaults.merge(options)` or `defaults.merge!(options)`
# is faster, I ran the following:
Benchmark.bm(7) do |x|
x.report("#merge:") do
10000000.times do
defaults = {:a => 1, :b => 2, :c => 3, :d => 4}
options = {:a => "another value", :d => true}
options = defaults.merge(options)
end
end
x.report("#merge!:") do
10000000.times do
defaults = {:a => 1, :b => 2, :c => 3, :d => 4}
options = {:a => "another value", :d => true}
options = defaults.merge!(options)
end
end
end
# on Ruby 2.6.7
# user system total real
# #merge: 11.822541 0.020036 11.842577 ( 11.905024)
# #merge!: 9.000405 0.000020 9.000425 ( 9.016654)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment