---
title: Use size over count or length
impact: LOW
impactDescription: Optimize performance by using the most efficient method.
tags: rails, performance, active-record, database
---

## Use size over count or length

Optimize performance by using the most efficient method. Use `size` instead of `count` or `length` for ActiveRecord collections. `size` intelligently chooses between `count` (SQL query if not loaded) and `length` (array size if already loaded).

**Incorrect:**

```ruby
# Always triggers a SELECT COUNT(*) query even if data is already loaded
users = User.all.to_a
puts users.count 
```

**Correct:**

```ruby
# Uses the array size if already loaded, otherwise queries DB
puts User.all.size
```

**Tools:** RuboCop (`Rails/SkipsModelValidations`)
