Memoization in Ruby on Rails

August 06, 2024

Hi, welcome! This is the second post on my blog (finally :P), and here I'll talk a little bit about memoization in RoR.

The first time I encountered memoization in Rails was at work a few months ago when I saw a method using something like @here ||= some_query. I was intrigued, started researching, and now I'm sharing what I've learned in this post!

What is memoization?

In simple terms, memoization is a way to store the result of a method call and return the cached result when the same inputs occur again.

It works by caching a method's results the first time it's called. After that, any subsequent calls will return the cached value instead of recalculating it.

Example of memoization in Rails

Memoization is commonly used in Rails applications to optimize methods that perform costly operations, like database queries or external API calls. Let's look at an example of a method before and after applying memoization:

Before memoization

class User < ApplicationRecord
  def expensive_method
    # Perform some costly operations here
    sleep(2) # Simulate a time-consuming task
    "Expensive result"
  end
end

user = User.find_by(id: 13)
puts user.expensive_method # This will take 2 seconds
puts user.expensive_method # This will take another 2 seconds

After memoization

class User < ApplicationRecord
  def expensive_method
    @expensive_method ||= begin
      # Perform some costly operations here
      sleep(2) # Simulate a time-consuming task
      "Expensive result"
    end
  end
end

user = User.find_by(id: 13)
puts user.expensive_method # This will take 2 seconds
puts user.expensive_method # This will be instant

The memoized version of the expensive_method uses the ||= operator to determine if the result has already been computed. The expensive operations are executed only during the first call, while subsequent calls return the cached result, which enhances performance.

Of course, this is a simplified example, but it shows how memoization can enhance your methods.

Benefits of memoization

There are several benefits to using memoization in Rails applications, but the ones I particularly noticed at work were:

  1. Increased performance: It makes things faster by reducing redundant operations.
  2. Simplified code: Makes your code cleaner by eliminating redundant calculations.

Use cases for memoization in Rails

Besides the benefits I experienced with memoization in the projects I’ve been working on, I also observed and want to highlight two scenarios where you definitely should consider applying memoization:

  1. Database queries: Avoid running the same query multiple times within the same request.
  2. Complex calculations: Store the results of complex calculations to improve performance.

However, it's important to remember that not all methods are good candidates for memoization. Generally, I recommend memoizing methods that:

  • The calculation is costly or takes a long time.
  • The input data doesn't change.
  • The method is used often.

In conclusion, memoization is beneficial when the method is called multiple times within the same context, reducing the overhead of redundant database queries and improving overall performance.

For now, that's all. I really hope you've learned something useful from this post!

puts "See ya :P"

Profile picture

Written by Mateus Elias using Gatsby, to share tech knowledge and personal experiences! You should follow him on GitHub.