Performance: Database query optimization
HIGH IMPACT
This affects how fast the page loads data from the database and how quickly the server responds to user requests.
posts = Post.includes(:comments).all posts.each do |post| puts post.comments.size end
posts = Post.all posts.each do |post| puts post.comments.count end
| Pattern | Database Queries | Data Transferred | Server Response Time | Verdict |
|---|---|---|---|---|
| N+1 queries | Many small queries (N+1) | More data due to repeated queries | High due to multiple DB hits | [X] Bad |
| Eager loading with includes | Few queries (usually 2) | Less repeated data | Lower due to fewer DB hits | [OK] Good |
| Selecting all columns | Single query | Large data size | Medium due to data size | [!] OK |
| Selecting needed columns | Single query | Minimal data size | Low due to less data | [OK] Good |
| Unindexed where clause | Single query | Depends on data | High due to full table scan | [X] Bad |
| Indexed where clause | Single query | Depends on data | Low due to index use | [OK] Good |