Skip to content

Instantly share code, notes, and snippets.

@czj
Created July 1, 2019 16:04
Show Gist options
  • Save czj/39b51b8c57a8b86fcc49449c85152d71 to your computer and use it in GitHub Desktop.
Save czj/39b51b8c57a8b86fcc49449c85152d71 to your computer and use it in GitHub Desktop.
Why is faster : ENV["key"] or ENV.key?("key") ? The answer will surprise you ...
require "benchmark/ips"
HASH = ("a".."zz").to_a.shuffle.to_h { |e| [e, "#{e}#{e}#{e}"] }
KEY = "zz"
def key_fast
HASH.key? KEY
end
def key_slow
HASH[KEY]
end
Benchmark.ips do |x|
x.report("Hash#[]") { key_slow }
x.report("Hash#key?") { key_fast }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment