Skip to content

Instantly share code, notes, and snippets.

@metaskills
Created August 30, 2010 16:53
Show Gist options
  • Save metaskills/557673 to your computer and use it in GitHub Desktop.
Save metaskills/557673 to your computer and use it in GitHub Desktop.
require 'bench_press'
extend BenchPress
author 'Ken Collins'
summary "Check and populate a options hash"
reps 100_000
measure "Hash#key?" do
o = {}
o[:d] = true unless o.key?(:d)
end
measure "Hash#merge!" do
{}.merge!(:key => :value)
end
measure "Hash#[]= Standard" do
{}[:key] = :value
end
measure "Hash#[]= Tricky" do
{}.[]=(:key, :value)
end
=begin
ruby 1.8.7 (2010-04-19 patchlevel 253) [i686-darwin10.4.0], MBARI 0x6770, Ruby Enterprise Edition 2010.02
----------------------------------------------------------------
Hash#[]= Standard 0.215189933776855 secs Fastest
Hash#[]= Tricky 0.21603798866272 secs 0% Slower
Hash#merge! 0.309281826019287 secs 30% Slower
Hash#merge 0.384943962097168 secs 44% Slower
ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10.4.0]
----------------------------------------------------------------
Hash#[]= Standard 0.150069952011108 secs Fastest
Hash#[]= Tricky 0.152034044265747 secs 1% Slower
Hash#merge! 0.227920055389404 secs 34% Slower
Hash#merge 0.303483963012695 secs 50% Slower
ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-darwin10.4.0]
--------------------------------------------------------------
Hash#[]= Tricky 0.103008031845093 secs Fastest
Hash#[]= Standard 0.103388071060181 secs 0% Slower
Hash#merge! 0.201750993728638 secs 48% Slower
Hash#merge 0.23440408706665 secs 56% Slower
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.4.0]
--------------------------------------------------------------
Hash#[]= Tricky 0.10367894172668457 secs Fastest
Hash#[]= Standard 0.10428905487060547 secs 0% Slower
Hash#merge! 0.18069767951965332 secs 42% Slower
Hash#merge 0.20720911026000977 secs 49% Slower
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment