Last active
December 12, 2023 08:47
-
-
Save lfender6445/86b603ca89c4ba2f961b to your computer and use it in GitHub Desktop.
Ruby - Hash#fetch vs #fetch with block performance
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
# Benchmarks time difference between TEST_HASH.fetch(:baz, '') and TEST_HASH.fetch(:baz) { '' } | |
p 'Key does not exist -----' | |
TEST_HASH = { foo: :bar } | |
def operation | |
TEST_HASH.fetch(:baz, '') | |
end | |
def elaboration_time(&block) | |
s = Time.now | |
yield | |
e = Time.now | |
e - s | |
end | |
t1 = elaboration_time do | |
100.times { operation } | |
end | |
p "Time fetch(:baz, ''):", t1 | |
def operation_2 | |
TEST_HASH.fetch(:baz) { '' } | |
end | |
t2 = elaboration_time do | |
100.times { operation_2 } | |
end | |
p "Time fetch(:baz){''}:", t2 | |
if t1 < t2 | |
puts 'fetch missing key WITHOUT block is faster than with a block' | |
else | |
puts 'fetch missing key WITH block is faster than with a block' | |
end | |
p 'Key does exist -----' | |
def operation_3 | |
TEST_HASH.fetch(:foo) { '' } | |
end | |
t3 = elaboration_time do | |
100.times { operation_3 } | |
end | |
p "Time fetch(:foo){''}:", t3 | |
def operation_4 | |
TEST_HASH.fetch(:foo, '') | |
end | |
t4 = elaboration_time do | |
100.times { operation_4 } | |
end | |
p "Time fetch(:foo){''}:", t4 | |
if t3 < t4 | |
puts 'fetch available key WITH block is faster than without a block' | |
else | |
puts 'fetch avaialable key WITHOUT a block is faster' | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hash#fetch performance with and without block
ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-darwin13.0]