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
size on an ActiveRecord collection.
Consider this example:
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
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
count can result in a noticeable performance boost.