简体   繁体   中英

How does Ruby Memoization work?

I heard about the benefits of memorization, but I am not sure how it works. For Example, in:

class User < ActiveRecord::Base
  def twitter_followers
    # assuming twitter_user.followers makes a network call
    @twitter_followers ||= twitter_user.followers
  end
end

as per my knowledge, @twitter_followers is an instance variable, and will only remain in the scope for one request (so that it will be accessible by the view.)

I am not sure if the same user refreshes the same page, whether it will use the cached result instead of firing the query.

You can have an instance of User and have user.twitter_followers calls in different places.

Without memoization it will mean new twitter_user.followers request with every call to user.twitter_followers , whereas with memoization only one request will be done and every consequent call will use set @twitter_followers variable.

So I am not sure if the same user refreshes the same page again will it use the cached result instead of firing the query?

With page refresh it will be new request.

In the view the advantage of memoization can be used, as my answer implies, for example if within this single page you are referencing user.twitter_followers more than once.

In models/services/workers/any other backend-related places having memoization really makes the difference.

First it will fire the query, It is stored in the memory as an instance variable of the User model's instance. The instance of User model will always be reloaded per request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM