Robert Klemme
1/26/2006 1:06:00 PM
James Edward Gray II wrote:
> On Jan 25, 2006, at 12:55 PM, Robert Klemme wrote:
>
>> So, basically I prefer Daniel's simpler approach - especially since
>> you can achieve the same: just create an instance that contains all
>> code (either directly or by delegation) that is expected to be slow
>> (and thus should be memoized) and memoize on that class.
>
> Can you show an example or two here? Using the current memoize.rb,
> how do we get objects A, B, and C using the same cache? I guess I'm
> having trouble getting my head around it.
class SillySomething
extend Memoizable
def initialize()
@a,@b,@c = A.new, B.new, C.new
# or other initialization
end
def calculate_foo(quirk, quark, quork)
x = @a.foo(quirk) + @b.doit(quark)
if x > 10
x += @c.doh(quork, @a)
else
x - 2
end
x
end
memoize :calculate_foo
end
The idea is to group relevant parts of your object model in a single class
and use an instance of that for memoization.
Maybe I can add an explanation to make it more clear: if you have a class
X with method Y that calculates something results of invoking Y on several
instances of X can only be memoized in the same cache if (i) either they
are not influenced by state of X instances or (ii) memoization somehow
uses this state to control lookup.
If (i) I don't see the point in having several objects that do exactly the
same calculation - methods might even be class methods (i.e. singleton
methods of the *single* class instance X). So there is actually no need
for a cache that covers several instances.
If (ii) you gain nothing by having a centralized cache because you'll have
to keep memoized values from different instances separate; in fact you add
a level of lookup (first object, then method and args - or do it in one
request with a larger key) and separate instance state from the instance.
IMHO that's inefficient, memory leaking and error prone.
Kind regards
robert