Skip to content

Commit

Permalink
Make Memoize more object shapes friendly
Browse files Browse the repository at this point in the history
  • Loading branch information
svoop committed Nov 4, 2023
1 parent 1219a5d commit ddae17a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
16 changes: 15 additions & 1 deletion lib/rodbot/memoize.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ module Rodbot
# e.either(5) # => 5 (recalculated, memoized anew)
# end
module Memoize

# Set up the memoize cache in the initializer in order to keep the number of
# object shapes low. There's still a fallback in the +memoize+ method for
# use cases where no object is instantiated.
#
# @see https://island94.org/2023/10/writing-object-shape-friendly-code-in-ruby
module Initializer
def initialize(...)
@_memoize_cache = {}
super
end
end

module ClassMethods
def memoize(method)
unmemoized_method = :"_unmemoized_#{method}"
Expand All @@ -54,7 +67,7 @@ def memoize(method)
send(unmemoized_method, *args, **kargs, &block)
else
id = method.hash ^ args.hash ^ kargs.hash
@_memoize_cache ||= {}
@_memoize_cache ||= {} # fallback memoize cache setup
if !Rodbot::Memoize.revisit? && @_memoize_cache.has_key?(id)
@_memoize_cache[id]
else
Expand Down Expand Up @@ -86,6 +99,7 @@ class << self
end

def included(base)
base.prepend(Initializer)
base.extend(ClassMethods)
end
end
Expand Down
2 changes: 1 addition & 1 deletion spec/lib/rodbot/concerns/memoize_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require_relative '../../../spec_helper'
#require_relative '../../../spec_helper'

class Either
include Rodbot::Memoize
Expand Down

0 comments on commit ddae17a

Please sign in to comment.