Wednesday, May 4, 2011

Speed up your counts in Rails 3

Just bumped into this and thought I would share. If you are trying to find the number of records that match two columns in your schema you might do this:

find_all_by_some_column_and_some_other_column('val', 'val2').count

What this does is select all of the data that matches and then does a count in Ruby. This is slower because it retrieves all of the data for every matching record. Whereas if you count like this:

where(:some_column => 'val', :some_other_column => 'val2').count

It will do the count in the database (which databases are really good at) and only return the total number of records that match. If you have 12 records it won't matter much which of the above you use. If you have 12,000 records the second will be incredibly faster.

No comments: