Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rails.cache.fetch perform better with memoization

I've searched and cannot seem to find a good source for whether it could be considered a good practice to combine methods for the following: When using memcached with the dalai gem and have a method that is called more than once for a request is there a performance advantage to using the second block over the first in a model? Is it considered good practice to use 'memoization' like this in conjunction with Rails.cache.fetch?

def total_ham
  Rails.cache.fetch("#{self.cache_key}/total_ham") do
    self.hams.sum(:metric_tons)
  end
end

or

def total_ham
  @total_ham ||= Rails.cache.fetch("#{self.cache_key}/total_ham") do
    self.hams.sum(:metric_tons)
  end
end
like image 865
Nathan W Avatar asked Oct 21 '22 18:10

Nathan W


1 Answers

If the total_ham method is called more than once per request, then you should memoize the result of the total_ham method even if you are fetching it out of the cache. The memoization will be faster than hitting the cache - due to the round-trip latency between your app server and the memcached server.

I can't say whether or not this is a best practice or not, but it's what I would do in your situation.

like image 163
mattr- Avatar answered Oct 27 '22 09:10

mattr-