Is every relavant calculation performed every time the page is loaded?

两盒软妹~` 提交于 2019-11-28 12:13:08

问题


I have a model "Wrapper", which has_many of another model "Category", which in turn has_many of another model, "Thing".

"Thing" has the integer attributes :count and :number. It also has an instance method defined as such in models/thing.rb:

def ratio
  (self.count + self.number).to_f / Thing.all.count.to_f
end

"Category", then, has this instance method, defined in models/category.rb:

def thing_ratios
  self.things.sum(&:ratio.to_f)
end

Finally, my wrapper.html.erb view shows Categories, listed in order of thing_ratios:

<%= @wrapper.categories.all.order(&:thing_ratios).each do |category| %>
  ...

My question is this: every time someone reloads the page wrapper.html.erb, would every single relavant calculation have to be recalculated, all the way down to self.count for every Thing associated with every Category on the page?


回答1:


In addition to the resources that @Kelseydh provided, you can also consider memoization for when you hit the same function multiple times as part of the same request. However, it will not retain its value after the request is processed.




回答2:


Yes it will be recalculated every time. If this is an expensive operation you should add a counter_cache (guide: http://railscasts.com/episodes/23-counter-cache-column) for the count and look into caching the query result using a service like memcache.

Many caching strategies exist, but for the database/Rails app itself Russian doll caching is considered the most flexible approach. If your data doesn't update often (meaning you don't need to worry about cache expiration often) you may be able to get way with page caching -- if so, count yourself lucky.

Some resources to get you started:

DHH on Russian Doll Caching: https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works).

Railscast on cache keys: http://railscasts.com/episodes/387-cache-digests

Advanced caching guide: http://hawkins.io/2012/07/advanced_caching_revised/

Not free, but I found this series was what really let me understand various forms of caching correctly: http://www.pluralsight.com/courses/rails-4-1-performance-fundamentals



来源:https://stackoverflow.com/questions/28492404/is-every-relavant-calculation-performed-every-time-the-page-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!