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

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
U
Unit 42
GbyAI
GbyAI
M
MIT News - Artificial intelligence
美团技术团队
罗磊的独立博客
雷峰网
雷峰网
量子位
博客园 - 【当耐特】
Last Week in AI
Last Week in AI
D
Docker
小众软件
小众软件
S
SegmentFault 最新的问题
Blog — PlanetScale
Blog — PlanetScale
阮一峰的网络日志
阮一峰的网络日志
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
WordPress大学
WordPress大学
V
V2EX
博客园_首页
腾讯CDC
The Cloudflare Blog
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

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
Count, Length, or Size? Avoiding ActiveRecord Performance...
Zil Norvilis · 2026-06-01 · via DEV Community

I remember when I first started with Rails, I thought .count, .length, and .size were exactly the same thing. I used them interchangeably in my views and controllers. If I wanted to know how many users were in the database, I would just pick one and move on.

But then, as my app grew and I started checking my server logs, I realized I was making a huge performance mistake. While these three methods look identical, they behave completely differently under the hood. One of them hits your database every single time, one of them might crash your server’s memory, and one of them is "smart" enough to choose the best path.

Here is the breakdown of when to use which so you can keep your Rails app fast.

1. .count (The Database Hitter)

When you call .count, ActiveRecord ignores any records you might already have loaded in memory. It goes straight to the database and runs a specific SQL query: SELECT COUNT(*) FROM users.

users = User.where(active: true)
users.count # SQL: SELECT COUNT(*) FROM users WHERE active = true

Enter fullscreen mode Exit fullscreen mode

When to use it: Use this when you only need the number and you have no intention of using the actual data.
The Trap: If you call .count and then immediately loop through the records with .each, you are doing double work. You hit the DB for the count, and then you hit it again to get the users.

2. .length (The Memory Loader)

Calling .length is the equivalent of saying: "Give me everything."

ActiveRecord will fetch every single column for every single record in that query and load them all into your computer's RAM. Only after everything is loaded does it count how many items are in the array.

users = User.where(active: true)
users.length # SQL: SELECT * FROM users WHERE active = true
# Every user object is now sitting in your RAM.

Enter fullscreen mode Exit fullscreen mode

When to use it: Use this only if you have already loaded the records (for example, if you already called @users.to_a).
The Trap: If you have 100,000 users and you just want to show a number in the navbar, calling .length will try to load all 100,000 users at once. This is the fastest way to get an "Out of Memory" error and crash your production server.

3. .size (The "Smart" Manager)

This is the method I recommend for 90% of use cases. It is the "omakase" choice because it adapts to the situation.

  • If the records are already loaded in memory, it acts like .length (it just counts the items in the array without touching the database).
  • If the records are not loaded, it acts like .count (it runs the efficient SELECT COUNT(*) query).
users = User.where(active: true)

# Records aren't loaded yet, so it runs a COUNT query
users.size 

# Later in the view...
users.each { |u| ... } # Data is loaded here

# Records are now loaded, so .size doesn't hit the DB again!
users.size 

Enter fullscreen mode Exit fullscreen mode

When to use it: This should be your default choice. It protects you from making mistakes in your views and ensures you aren't hammering the database with redundant queries.

Summary: The Decision Matrix

Method Behavior Best for...
.count Always runs SELECT COUNT(*) One-off checks when you don't need the data.
.length Always runs SELECT * When data is already loaded in an array.
.size Smart: Choice depends on state Almost everything. It’s the safest default.

As a solo developer, you want to spend your time building features, not debugging slow database queries. Switching your habit from .count to .size is a 1-second change that can save you a lot of headache in the future.