Reserve counter of caches against calculation

I have a collection in which I want to show totals, and the idea was to use a cache for each of the totals that I need. However, I will also need to expand in the dataset. Therefore, most likely, I will have to download the collection. So should I use cache or just use calculation?

+4
source share
2 answers

The answer depends on the size of the collection. If the collection is very large (1000 or items), then caching is probably a good idea. If there are only a few, and you have indexes on the tables to quickly find the corresponding rows, then the cache is probably not needed, especially if you still need to expand the collection.

As with all such questions, the correct answer is usually "dependent". It very much depends on your requirements and data, etc.

+3
source

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 do with these calculations on the page . For example, if you are making the β€œBlog” application, and the posts / index page displays 10 blog posts, each of which contains β€œ155 comments” below, this causes a lot of database queries that can be avoided with a cache counter.

I suggest trying it only with active search for entries, but add the option to "enable". Suppose message # 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 message and 1 for each comment. Instead, you can:

 Post.find_by_id(123, :include => [:comments]) 

Now it will automatically request comments when searching for a message, folding 51 requests to 1.

+3
source

All Articles