Memoization

I noticed a really interesting feature coming in Rails 2.2 called “Memoization”.  It means caching the return value of a method. If your method is called multiple times the cache value is returned rather then the executing the method again.  This is something I do in every application for

def current_user
@current_user ||= User.find(session[:current_user_id])
end

In the new Rails 2.2, you can have the same behavior with the “memoize” declaration

memoize :current_user
def current_user
User.find(session[:current_user_id])
end

Regardless of how many times I call current_user, Rails will only do one DB query.

This level of caching is very common and we always use it in practice with instance variables and singleton patterns. Its nice to see a declarative way to do this in Rails. Learning a new software term like “Memoization” is a bonus.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: