Reputation: 4201
I have a collection which I want to show totals for, and the idea was to use a cache for each of the totals I need. However I also will need to drill down into the data set. So most likely I will have to load the collection anyway. So should I still use the cache or just use a calculation?
Upvotes: 4
Views: 1858
Reputation: 25659
As Stephen ODonnell said, "...depends on the size of the collection." However, you also need to take into account the number of times that you will be doing this calculation per page. For example, if you're doing a Blog application and the posts/index page shows 10 blog posts, each with "155 Comments" at the bottom, that's a lot of database calls that can be avoided by using a counter cache.
I suggest trying it with just the active record searching, but add the "include" option. Assume Post # 123 has 50 comments.
p = Post.find_by_id(123)
p.comments.each do {|c| puts c } #Do something meaningful instead...
Will generate 51 database calls, 1 for the Post, and 1 for each comment. Instead, you can do:
Post.find_by_id(123, :include => [:comments])
Now it will automatically query for the comments when you search for the post, collapsing 51 queries into 1.
Upvotes: 4
Reputation: 4466
The answer depends on the size of the collection. If the collection is very large (1000's or items), then caching is probably a good idea. If its only a handful and you have indexes on the tables to quickly find the relevant rows, then a cache is probably not required, especially if you have to drill into the collection anyway.
As with all these sort of questions, the correct answer is usually 'it depends'. It very much depends on your requirements and data etc.
Upvotes: 3