What does Memoization mean?

I was watching a screencast the other day and the person mentioned in the video: “… and this gives you an mm(…) array”. The (..) means that I did not understand what I had just heard. I admit that I rewinded the video a few times and I could only grasp something along the lines of ‘memorized array’. It was then that I googled this and was autocorrected to “memoization”. WAT?

It turns out that memoization is recording the results of earlier calculations so that we don’t have to repeat the calculations again. It simply means caching the output.

An example may clarify this further. Say I have method that tells me how many Twitter followers a user has:

def total_twitter_followers
  current_user.twitter_followers
end

This is perfectly valid, however, every time we call this method during one request it always calls the Twitter API for the result. By memoizing the call, you store the value thus avoiding expensive fetches again:

def total_twitter_followers
  @current_user_total_followers ||= current_user.twitter_followers
end

The ||= operator is a so-called conditional assignment that only assigns the value on its right to the variable on its left if the variable is not true. Since pretty much everything in Ruby evaluates to true when coerced into a boolean (except nil and, of course, false, as well as a couple of other things) this is exactly what we want: The first call returns the actual string and from the second time on, no matter how often the method is called on the same object, the “cached” result will be used.

Hope you learned something today.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s