惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
GbyAI
GbyAI
aimingoo的专栏
aimingoo的专栏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence
腾讯CDC
博客园 - Franky
Engineering at Meta
Engineering at Meta
C
Check Point Blog
T
The Blog of Author Tim Ferriss
有赞技术团队
有赞技术团队
Microsoft Azure Blog
Microsoft Azure Blog
MyScale Blog
MyScale Blog
I
InfoQ
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
N
Netflix TechBlog - Medium
Last Week in AI
Last Week in AI
S
SegmentFault 最新的问题
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop Guessing Between .count, .length, and .size in Rails
Pavel Myslik · 2026-06-18 · via DEV Community

When investigating a slow Rails endpoint, it's common to start by looking for N+1 queries, missing indexes, or expensive joins. Sometimes, though, the real culprit is much smaller.

It might be hiding in a method call you've written hundreds of times without thinking about it.

In Rails, .count, .length, and .size all return a number, and many developers use them interchangeably. Under the hood, however, they behave very differently.

Let's break down how each method works and see which one is the right choice for different situations.


.count: Always Hits the Database

.count runs a SQL COUNT(*) query every single time you call it:

post.comments.count
# SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = 1

This is great when you only need a number and don't need the records themselves. The database does the counting and returns a single integer, without loading any records into memory.

But there's a catch that surprises people.

.count ignores records that are already loaded. Even if you've just pulled the whole association into memory, calling .count fires another query:

post.comments.load
# Loads objects into memory
post.comments.count
# SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = 1

This means repeated calls to .count can generate unnecessary database queries, even when the records are already loaded.


.length: Always Counts in Memory

Unlike .count, .length doesn't ask the database for a count.

If the association has not been loaded yet, Rails first loads every matching record into memory, with all of its columns, and only then counts them:

post.comments.length
# SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1

That means a simple call to .length on a post with 10,000 comments will instantiate 10,000 Comment objects just to return a number.

On the other hand, .length shines when the association has already been loaded:

post.comments.load
# Loads objects into memory
post.comments.length
# => 10000

No additional query is executed. Rails simply counts the records already in memory.

In other words, .length behaves like an Array. If the records are already there, it's free. If they aren't, Rails has to load them all first.


.size: The Adaptive One

.size combines the best parts of .count and .length.

If the association has not been loaded yet, .size behaves like .count and executes a lightweight COUNT(*) query:

post.comments.size
# SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = 1

But once the association has already been loaded, .size behaves like .length and simply counts the records already in memory:

post.comments.load
# Loads objects into memory
post.comments.size
# => 10000

No additional query is executed.

In short, .size adapts to the association's current state, avoiding both unnecessary record loading and redundant COUNT(*) queries.

That's why .size is often the best default choice.

Bonus: .size and Counter Cache

If a counter_cache is set up, .size can skip the database entirely:

class Comment < ApplicationRecord
  belongs_to :post, counter_cache: true
end

Rails now keeps a comments_count column on posts table, and .size reads it directly. No COUNT(*), no records loaded:

post.comments.size
# => 10000  (reads post.comments_count)


A Rule of Thumb

  • Use .count when you always want the latest value from the database.
  • Use .length when you've already loaded the records and just need to count them in memory.
  • Use .size when you want Rails to choose the most efficient option automatically.

And if you remember just one thing: in most cases, .size is the safest default, because it adapts to the current state of the association.

This is part of a small series on subtle ActiveRecord behaviors that quietly affect performance. The first post covered .any? vs .exists? and the same kind of hidden cost.