Skip to content

Instantly share code, notes, and snippets.

@vasilakisfil
Created November 16, 2018 10:59
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 vasilakisfil/6bd0375681ba65d8b6fa1d3cf2e720bd to your computer and use it in GitHub Desktop.
Save vasilakisfil/6bd0375681ba65d8b6fa1d3cf2e720bd to your computer and use it in GitHub Desktop.
Accessing a hash value by key is extremely fast. Is it possible to access the value of the first key with the same performance ?
require 'benchmark/ips'
require 'faker'
_hash = 100.times.inject({}){|hash, i|
hash[Faker::Lorem.word] = Faker::Lorem.word
hash
}
_hash[:aaa] = 'a'
HASH = _hash
def first_key1
HASH.keys.first
end
def first_key2
HASH.first[0]
end
def first_key3
HASH[:aaaa]
end
Benchmark.ips do |x|
x.report('first_key1') { first_key1 }
x.report('first_key2') { first_key2 }
x.report('first_key3') { first_key3 }
x.compare!
end
#Warming up --------------------------------------
# first_key1 198.267k i/100ms
# first_key2 181.968k i/100ms
# first_key3 340.302k i/100ms
#Calculating -------------------------------------
# first_key1 3.171M (± 4.8%) i/s - 15.861M in 5.014686s
# first_key2 2.599M (± 9.4%) i/s - 12.920M in 5.022006s
# first_key3 8.260M (±17.7%) i/s - 39.475M in 5.004442s
#
#Comparison:
# first_key3: 8260385.4 i/s
# first_key1: 3171219.2 i/s - 2.60x slower
# first_key2: 2599325.1 i/s - 3.18x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment