matthewrudy / memoist

ActiveSupport::Memoizable with a few enhancements
MIT License
920 stars 99 forks source link

Garbage Collection? #65

Closed pt-stripe closed 7 years ago

pt-stripe commented 7 years ago

How do you deal with garbage collection? I couldn't see anywhere in your docs, and the code got a big convoluted while tracing it for me to discern. Basically, do you free the memory here:

class Person
  def taxes_due(income)
    income * 0.40
  end
  memoize :taxes_due
end

a = Person.new
a.taxes_due(100_000)
a = nil

or will it hold on to that memoized value for the whole life of the program?

Similarly, if you take a parameter and then the last reference to the param goes away, will you still hold on to it? Like:

class Foo
  def bar(baz)
    "1"
  end
  memoize :bar
end

a = Foo.new
a.bar(Object.new)
matthewrudy commented 7 years ago

@pt-stripe so memoization without arguments is much simpler.

Its pretty much equivalent to

def foo
  @foo ||= bar
end

So unsurprisingly that instance variable is cleared when the instance is cleared.

For a method with arguments, it's more complicated. But something like

def foo(bar)
  @foo ||= {}
  @foo[bar] ||= baz
end

Unsurprisingly that retains any argument bar for the life of the instance.

Notably, I don't use memoize on a method with args. Seems nifty, but not a nice solution.

pt-stripe commented 7 years ago

Thanks @matthewrudy. Are you literally storing the value on the object? If so, how do you memoize on frozen objects?

matthewrudy commented 7 years ago

@pt-stripe yes.

It's memoized values are stored as instance variables, so we don't memoize frozen objects.

It just wouldn't work.

pt-stripe commented 7 years ago

Ok, I was hoping you had a magic solution, but alas :) Thanks for the info!