From 81b2ff0cbb2d4df262f948674b111c2fbf45f8f0 Mon Sep 17 00:00:00 2001 From: Jemma Issroff Date: Tue, 4 Jan 2022 10:25:15 -0500 Subject: [PATCH] Fixed fetch call --- lib/memo_wise.rb | 22 ++-------------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/lib/memo_wise.rb b/lib/memo_wise.rb index 873428cc..0e949ddb 100644 --- a/lib/memo_wise.rb +++ b/lib/memo_wise.rb @@ -107,10 +107,7 @@ def #{method_name} memo_wise_module.module_eval <<~HEREDOC, __FILE__, __LINE__ + 1 def #{method_name}(#{MemoWise::InternalAPI.args_str(method)}) _memo_wise_hash = (_memo_wise[:#{method_name}] ||= {}) - _memo_wise_output = _memo_wise_hash[#{key}] - if _memo_wise_output || _memo_wise_hash.key?(#{key}) - _memo_wise_output - else + _memo_wise_hash.fetch(#{key}) do _memo_wise_hash[#{key}] = super end end @@ -118,27 +115,12 @@ def #{method_name}(#{MemoWise::InternalAPI.args_str(method)}) # MemoWise::InternalAPI::MULTIPLE_REQUIRED, MemoWise::InternalAPI::SPLAT, # MemoWise::InternalAPI::DOUBLE_SPLAT, MemoWise::InternalAPI::SPLAT_AND_DOUBLE_SPLAT else - # NOTE: When benchmarking this implementation against something like: - # - # @_memo_wise.fetch(key) do - # ... - # end - # - # this implementation may sometimes perform worse than the above. This - # is because this case uses a more complex hash key (see - # `MemoWise::InternalAPI.key_str`), and hashing that key has less - # consistent performance. In general, this should still be faster for - # truthy results because `Hash#[]` generally performs hash lookups - # faster than `Hash#fetch`. memo_wise_module.module_eval <<~HEREDOC, __FILE__, __LINE__ + 1 def #{method_name}(#{MemoWise::InternalAPI.args_str(method)}) _memo_wise_hash = (_memo_wise[:#{method_name}] ||= {}) _memo_wise_key = #{MemoWise::InternalAPI.key_str(method)} - _memo_wise_output = _memo_wise_hash[_memo_wise_key] - if _memo_wise_output || _memo_wise_hash.key?(_memo_wise_key) - _memo_wise_output - else + _memo_wise_hash.fetch(_memo_wise_key) do _memo_wise_hash[_memo_wise_key] = super end end