Created
July 1, 2019 16:04
-
-
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 ...
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 "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