On Saturday, September 8, 2012 6:25:30 AM UTC+1, bricker wrote:
>
> [snip]
> Line 1 will perform a database query no matter what, on every page load. 
> It also requires several hits to the cache database to check for every 
> blog's `cache_key`.
> If any post in a blog is updated, that block will be required to render 
> the post partial 5 times, no matter what. It will also have to fire off a 
> query to the database to retrieve those 5 posts. At this point - with the 5 
> posts loaded in to memory, and the partials being rendered anyways - what 
> is really the performance difference between fetching the HTML fragment for 
> that post from cache, or just rendering the partial as usual? My guess is 
> that it's negligible, but I hope that I am wrong.
>
> Why guess - benchmark it. It will certainly depend on the complexity of 
what's going on inside your partials

[snip] 
 

> This method (on cache hit):
> * Will not perform any database queries
> * Doesn't need to instantiate an ActiveRecord::Relation object
> * Doesn't render any partials
> * Only needs to check the cache for a single key
>
> The only downside, of course, is that the cache needs to be manually 
> expired - but that's, what, 5 lines in an observer?
>
> **post_observer.rb**
> 1. class PostObserver < ActiveRecord::Observer
> 2.   def after_save(post)
> 3.     ActionController::Base.new.expire_fragment "views/recent_posts"
> 4.   end
> 5. end
>
> Of course, if you have a lot of places where this object is being 
> represented, you'd have to expire several fragments. But, with redis, you 
> can take advantage of `sets` and `smembers` to do that.
>
> auto expiring keys also require extra writing to the database to update 
> associated objects (such as a Blog) when a Post is saved.
>
>
I think the main thrust of DHH's post wasn't "this is the absolutely 
fastest way of implementing caching" but "this is the easy way to cache 
stuff without screwing up cache expiration", which I think is hard to 
perceive with a simple  blog example. Sweeper and so on also get harder 
when you want to deal with fine grained caching. Say for example that in 
addition to what you've outlined above, there's also a tags page for each 
post (which caches its content), a way for users to have a page of their 
favourite posts, a 'featured posts section'. Now your 5 line post observer 
is getting quite complicated and has to know an awful lot about the 
structure of your site.


Fred

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/ivAQmVg3-GsJ.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to