Ruby on Rails, Io, Lisp, JavaScript, Dynamic Languages, Prototype-based programming and more...

Friday, June 16, 2006

Caching Computations During Request Processing Even Better

In a recent post by Stefan Kaes from RailsExpress, Stefan mentions a method I have often used for speeding things up a bit.

module M
def get_data_for(request)
@cached_data_for_request ||=
begin
expensive computation depending on request returning data
end
end
end

However the problem with this method is that if get_data_for(request) returns nil, it will keep performing the request over and over again. Here is a slightly improved version if you don't always expect to get a return value.

module M
def get_data_for(request)
unless @cached_data_found
@cached_data_found = true
@cached_data_for_request =
begin
expensive computation depending on request returning data
end
end
@cached_data_for_request
end
end

0 Comments:

Post a Comment

<< Home