Skip to content

Instantly share code, notes, and snippets.

@jhliberty
Forked from postmodern/hash_merge_benchmark.rb
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save jhliberty/3fea29a8d9c79847fc9a to your computer and use it in GitHub Desktop.

Select an option

Save jhliberty/3fea29a8d9c79847fc9a to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'benchmark'
Benchmark.bm do |b|
n = 1_000_000
hash1 = {a: 1, b: 2, c: 3}
hash2 = {x: 1, y: 2, z: 3}
b.report('Hash#merge') do
n.times { {a: 1, b: 2, c: 3}.merge(hash2) }
end
b.report('keyword args') do
n.times { {a: 1, b: 2, c: 3, **hash2} }
end
end
@jhliberty
Copy link
Copy Markdown
Author

user     system      total        real

Hash#merge 1.540000 0.000000 1.540000 ( 1.550766)
keyword args 0.650000 0.000000 0.650000 ( 0.648758)

@jhliberty
Copy link
Copy Markdown
Author

the results are much closer with Hash#update:

   user     system      total        real

Hash#merge 1.750000 0.010000 1.760000 ( 1.757309)
Hash#update 0.750000 0.000000 0.750000 ( 0.752853)
keyword args 0.700000 0.010000 0.710000 ( 0.709861)

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