Skip to content

Instantly share code, notes, and snippets.

@postmodern
Created March 29, 2013 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save postmodern/5274138 to your computer and use it in GitHub Desktop.
Save postmodern/5274138 to your computer and use it in GitHub Desktop.
Benchmark of Hash#merge vs. Ruby 2.0 keyword arguments.
#!/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
@postmodern
Copy link
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)

@dkubb
Copy link

dkubb commented Mar 30, 2013

@postmodern 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)

EDIT: apparently I didn't understand the context of the benchmark: https://twitter.com/raggi/status/317903577668534272

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