Skip to content

Instantly share code, notes, and snippets.

@huacnlee
Created September 30, 2014 07:48
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 huacnlee/d97c03866e537d628cff to your computer and use it in GitHub Desktop.
Save huacnlee/d97c03866e537d628cff to your computer and use it in GitHub Desktop.
Ruby hash.keys.index vs hash.has_key?
Calculating -------------------------------------
keys.index 1794 i/100ms
has_key? 1822 i/100ms
-------------------------------------------------
keys.index 4036912.9 (±10.4%) i/s - 8691930 in 2.275054s
has_key? 6605458.9 (±9.1%) i/s - 25340376 in 3.878441s
Comparison:
has_key?: 6605458.9 i/s
keys.index: 4036912.9 i/s - 1.64x slower
hash = { foo: 1, bar: 2, dar: 3 }
Benchmark.ips do |x|
x.report("keys.index") {
hash.keys.index(:foo)
}
x.report("has_key?") {
hash.has_key?(:foo)
}
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment