Caching method calls - Is this of interest to anyone?

F

Farrel Lifson

Hi folks,

I've been trying to improve my metaprogramming skills the past two
weeks and came up with the following library which caches specific
method calls transparently so you don't have to explicitly save the
result. Is it interesting to anyone out there? If so I'll gemify it
and release it. A quick example:

require 'cachablemethods'

def timer(start,result,finish)
puts "Computed value #{result} in #{finish - start} seconds"
end

class Foo
include CachableMethods
def bar(num)
sleep(5)
rand(num)
end

def baz
sleep(5)
return yield(rand(1000))
end

def baq
sleep(5)
rand(1000)
end
cache_method :bar,:baz,:baq
end

foo = Foo.new

puts "Initial calls cached"
timer(Time.new,foo.bar(1000),Time.new)
timer(Time.new,foo.baz{|n| n*2},Time.new)
timer(Time.new,foo.baq,Time.new)

puts "Calling method without parameters/blocks return cached result"
timer(Time.new,foo.bar,Time.new)
timer(Time.new,foo.baz,Time.new)
timer(Time.new,foo.baq,Time.new)

puts "Calling methods with parameters/blocks or ending with ! if it
takes neither recaches values"
timer(Time.new,foo.bar(1000),Time.new)
timer(Time.new,foo.baz{|n| n*3},Time.new)
timer(Time.new,foo.baq!,Time.new)

farrel@nicodemus ~/Projects/cachable/lib $ ruby test.rb
Initial calls cached
Computed value 516 in 4.998986 seconds
Computed value 1848 in 4.999224 seconds
Computed value 200 in 4.999236 seconds
Calling method without parameters/blocks return cached result
Computed value 516 in 3.6e-05 seconds
Computed value 1848 in 2.0e-05 seconds
Computed value 200 in 2.1e-05 seconds
Calling methods with parameters/blocks or ending with ! if it takes
neither recaches values
Computed value 935 in 4.998461 seconds
Computed value 648 in 4.999118 seconds
Computed value 83 in 4.99987 seconds

Farrel
 
T

Trans

Robert said:

It would be of interest to compare implimentations. There are a few out
there.

Also a vague notion, but would it be possible to create such a cache
that is "per original call"? Let say I call #x and it calls #y, #y, and
#z where #y is cached. So #y only happens once actually. But if I call
another method #q that's calls #y it would do it again for #q. Make
sense? I _think_ that would be equivalent to task a dependency system
(like Rake).

T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top