Skip to content

Instantly share code, notes, and snippets.

@gdiggs
Created February 28, 2015 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdiggs/97c9407d2ba8663f9c3e to your computer and use it in GitHub Desktop.
Save gdiggs/97c9407d2ba8663f9c3e to your computer and use it in GitHub Desktop.
Testing Hash[] instead of #dup
require 'benchmark/ips'
def quux(hash_arg)
hash_arg = hash_arg.dup
10.times { |i| hash_arg.merge!({ "num_#{i}" => i }) }
end
def corge(hash_arg)
hash_arg = Hash[hash_arg]
10.times { |i| hash_arg.merge!({ "num_#{i}" => i }) }
end
Benchmark.ips do |x|
x.report("merge! with dup") { quux({}) }
x.report("merge! with Hash[]") { corge({}) }
x.compare!
end
Calculating -------------------------------------
merge! with dup 4.759k i/100ms
merge! with Hash[] 4.863k i/100ms
-------------------------------------------------
merge! with dup 52.455k (± 3.7%) i/s - 266.504k
merge! with Hash[] 53.576k (± 3.7%) i/s - 267.465k
Comparison:
merge! with Hash[]: 53575.8 i/s
merge! with dup: 52454.7 i/s - 1.02x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment