Skip to content

Instantly share code, notes, and snippets.

@lfender6445
Last active December 12, 2023 08:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfender6445/86b603ca89c4ba2f961b to your computer and use it in GitHub Desktop.
Save lfender6445/86b603ca89c4ba2f961b to your computer and use it in GitHub Desktop.
Ruby - Hash#fetch vs #fetch with block performance
# 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
@lfender6445
Copy link
Author

Hash#fetch performance with and without block

ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-darwin13.0]

  • fetch a missing key WITHOUT block is significantly faster than with a block
  • fetch available key WITH block is faster than without a block

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment