Sunday, May 5, 2013

Size vs Count and their role in Rails App Performance


If you have ever used the concept of Counter Cache in Rails, one thing you must know that the usage of count differs from the usage of size in Rails.

Say for e.g., If I have a counter cache column in my Posts Table that gives me the count of the number of comments.

1.9.3p327 :008 > p = Post.find_by_id(234)


1.9.3p327 :008 > p.comments.size
=> 0
1.9.3p327 :009 > p.comments.count
  (0.5ms)  SELECT COUNT(*) FROM `comments` WHERE `comments`.`commentable_id` = 51565 AND `comments`.`commentable_type` = 'Post'
=> 0

From the above one can conclude:-

size -> refers to the counter cache column and doesn't hit the DB. This way the response time is improved and it guarantees better performance for your app.

count -> makes a query to the DB as you can see(above) and this way your App's Table inspite of having a counter cache column might not be using it .