Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

lfender6445 commented Nov 19, 2014

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
You can’t perform that action at this time.