Reputation: 4388
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.
Upvotes: 2
Views: 516
Reputation: 52357
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.
Upvotes: 3
Reputation: 21
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.
Upvotes: 1