Beware of ActiveRecord::Calculations.count

Today, whilst engaged in some performance debugging, I discovered what I would assume is, to most, an easily missed intricacy of ActiveRecord. I am referring to the difference between using count and size on an ActiveRecord collection.

Consider this example:

Whereas calling size on an ActiveRecord collection simply counts the elements in the ruby array, the count method actually generates a SQL query. No doubt, this behavior is intended, though it is a bit confusing, given that calling size and count on a Ruby array are nearly identical, at least when count is not passed anything.

The differences here may seem trivial, but when iterating over a large collection of ActiveRecord objects, simply substituting size for count can result in a noticeable performance boost.

Notes

  1. anneliese-wright reblogged this from alexjsharp
  2. alexjsharp posted this