Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created April 4, 2012 21:14
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 ahoward/2305719 to your computer and use it in GitHub Desktop.
Save ahoward/2305719 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/object/try'
n = 1_000_000
options = {:k => :v}
url_options = {:host => 'http://dojo4.com'}
[ {:k => :v}, nil ].each do |options|
Benchmark.bm do |bm|
##
#
bm.report "options=#{ options.inspect } - old clever" do
n.times do
(options || {}).reverse_merge(url_options).symbolize_keys
end
end
##
#
bm.report "options=#{ options.inspect } - new clever" do
n.times do
(options || {}).symbolize_keys.reverse_merge!(url_options)
end
end
##
#
bm.report "options=#{ options.inspect } - simple+correct" do
n.times do
dst = {}
options.keys.each do |k|
k = k.to_sym
dst[k] = options[k] unless dst.has_key?(k)
end if options
url_options.keys.each do |k|
k = k.to_sym
dst[k] = url_options[k] unless dst.has_key?(k)
end if url_options
dst
end
end
##
#
bm.report "options=#{ options.inspect } - clever+correct" do
n.times do
Hash[ (url_options.to_a + options.to_a).each{|kv| kv[0] = kv[0].to_sym} ]
end
end
end
end
__END__
user system total real
options=nil - old clever 3.310000 0.040000 3.350000 ( 3.351594)
options=nil - new clever 1.650000 0.010000 1.660000 ( 1.669478)
options=nil - simple+correct 1.380000 0.020000 1.400000 ( 1.406858)
options=nil - clever+correct 1.950000 0.010000 1.960000 ( 1.952443)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment