Created
January 18, 2012 09:44
-
-
Save schmurfy/1632199 to your computer and use it in GitHub Desktop.
Ruby: Intelligent hash benchmarks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'extlib/mash' | |
require 'active_support/hash_with_indifferent_access' | |
GC.disable | |
h1 = {'a' => "toto", 45 => "yeah", :a_symbol => "a string"} | |
h2 = HashWithIndifferentAccess.new(h1) | |
h3 = Hash.new {|hash,key| hash[key.to_s] if Symbol === key } | |
h3['a_symbol'] = "another string" | |
h4 = Mash.new | |
h4['a_symbol'] = "yet another string" | |
def bench(label, count = 1_000_000) | |
started_at = Time.now.to_f | |
count.times do | |
raise unless yield | |
end | |
elapsed = (Time.now.to_f - started_at) * 1000 | |
puts "#{label.rjust(30, ' ')} : #{'%.2f' % elapsed} ms" | |
end | |
bench("standard by string") do | |
h1['a'] == "toto" | |
end | |
bench("standard by symbol") do | |
h1[:a_symbol] == "a string" | |
end | |
puts "" | |
bench("ar by string") do | |
h2['a_symbol'] == "a string" | |
end | |
bench("ar by symbol") do | |
h2[:a_symbol] == "a string" | |
end | |
puts "" | |
bench("hash with block by string") do | |
h3['a_symbol'] == "another string" | |
end | |
bench("hash with block by symbol") do | |
h3[:a_symbol] == "another string" | |
end | |
puts "" | |
bench("mash by string") do | |
h4['a_symbol'] == "yet another string" | |
end | |
bench("mash by symbol") do | |
h4[:a_symbol] == "yet another string" | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# standard by string : 323.49 ms | |
# standard by symbol : 212.77 ms | |
# | |
# ar by string : 349.31 ms | |
# ar by symbol : 922.98 ms | |
# | |
# hash with block by string : 345.58 ms | |
# hash with block by symbol : 686.17 ms | |
# | |
# mash by string : 472.66 ms | |
# mash by symbol : 1209.67 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment