In Rails, you can find the number of records using both Model.size
and Model.count
. If you're dealing with more complex queries is there any advantage to using one method over the other? How are they different?
For instance, I have users with photos. If I want to show a table of users and how many photos they have, will running many instances of user.photos.size
be faster or slower than user.photos.count
?
Thanks!
Sometimes
size
"picks the wrong one" and returns a hash (which is whatcount
would do)In that case, use
length
to get an integer instead of hash.You should read that, it's still valid.
You'll adapt the function you use depending on your needs.
Basically:
if you already load all entries, say
User.all
, then you should uselength
to avoid another db queryif you haven't anything loaded, use
count
to make a count query on your dbif you don't want to bother with these considerations, use
size
which will adaptAs the other answers state:
count
will perform an SQLCOUNT
querylength
will calculate the length of the resulting arraysize
will try to pick the most appropriate of the two to avoid excessive queriesBut there is one more thing. We noticed a case where
size
acts differently tocount
/length
altogether, and I thought I'd share it since it is rare enough to be overlooked.If you use a
:counter_cache
on ahas_many
association,size
will use the cached count directly, and not make an extra query at all.This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.
The following strategies all make a call to the database to perform a
COUNT(*)
query.The following is not as efficient as it will load all records from the database into Ruby, which then counts the size of the collection.
If your models have associations and you want to find the number of belonging objects (e.g.
@customer.orders.size
), you can avoid database queries (disk reads). Use a counter cache and Rails will keep the cache value up to date, and return that value in response to thesize
method.