Mark Chavez
eat. sleep. repeat. 👾 coding, ⌨️ keyboarding, 🚴🏼 cycling.
Counting things in ActiveRecord 08/03/2023
The .count method

When called on a ActiveRecord::Relation object, it performs a COUNT() sql query. This call is not memoized. It will perform the query every time count is called. Calling count on an Array object is usually slower than its AR counterpart.

The .size method

When records are not yet loaded (lazy), this method performs a COUNT() sql query. However when records are already loaded, size method behaves like it’s called from an array object.

The .length method

ActiveRecord::Relation does not implement its own length method so result are always converted to array.