Skip to content

Instantly share code, notes, and snippets.

@drbrain
Created November 2, 2017 22:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drbrain/4df51902c6086ddf519088ce661de86f to your computer and use it in GitHub Desktop.
Save drbrain/4df51902c6086ddf519088ce661de86f to your computer and use it in GitHub Desktop.
Don't convert hash keys, it's slower than using the "natural" key of the input data
$ ruby -v t.rb
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin17]
Lookup
Warming up --------------------------------------
Symbol Hash, Symbol Key
259.197k i/100ms
String Hash, String Key
231.953k i/100ms
Symbol Hash, String Key
203.959k i/100ms
String Hash, Symbol Key
197.515k i/100ms
Calculating -------------------------------------
Symbol Hash, Symbol Key
6.998M (± 2.9%) i/s - 34.992M in 5.004735s
String Hash, String Key
5.407M (± 2.4%) i/s - 27.139M in 5.021924s
Symbol Hash, String Key
4.018M (± 1.5%) i/s - 20.192M in 5.026624s
String Hash, Symbol Key
3.788M (± 2.2%) i/s - 18.961M in 5.008168s
Comparison:
Symbol Hash, Symbol Key: 6997934.0 i/s
String Hash, String Key: 5407394.5 i/s - 1.29x slower
Symbol Hash, String Key: 4017928.8 i/s - 1.74x slower
String Hash, Symbol Key: 3788016.8 i/s - 1.85x slower
require "benchmark/ips"
STRING_KEYS = (1..1000).map{|x| "key_#{x}"}.shuffle
FROZEN_KEYS = STRING_KEYS.map{|x| "fr_#{x}".freeze}
SYMBOL_KEYS = STRING_KEYS.map(&:to_sym)
# If we use static values for Hash, speed improves even more.
def symbol_hash
SYMBOL_KEYS.collect { |k| [ k, rand(1..100)]}.to_h
end
def string_hash
STRING_KEYS.collect { |k| [ k, rand(1..100)]}.to_h
end
# See this article for the discussion of using frozen strings instead of symbols
# http://blog.arkency.com/could-we-drop-symbols-from-ruby/
def frozen_hash
FROZEN_KEYS.collect { |k| [ k, rand(1..100)]}.to_h
end
SYMBOL_HASH = symbol_hash
STRING_HASH = string_hash
FROZEN_HASH = frozen_hash
def lookup_symbol_hash_from_string
SYMBOL_HASH[STRING_KEYS.sample.to_sym]
end
def lookup_string_hash_from_symbol
STRING_HASH[SYMBOL_KEYS.sample.to_s]
end
def lookup_string_hash_from_string
STRING_HASH[STRING_KEYS.sample]
end
def lookup_symbol_hash_from_symbol
SYMBOL_HASH[SYMBOL_KEYS.sample]
end
Benchmark.ips do |x|
puts "Lookup"
x.report("Symbol Hash, Symbol Key") { lookup_symbol_hash_from_symbol }
x.report("String Hash, String Key") { lookup_string_hash_from_string }
x.report("Symbol Hash, String Key") { lookup_symbol_hash_from_string }
x.report("String Hash, Symbol Key") { lookup_string_hash_from_symbol }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment