Performance: N+1 detection tools
This concept affects page load speed by reducing unnecessary database queries that delay content rendering.
posts = Post.includes(:author).all posts.each do |post| puts post.author.name end
posts = Post.all posts.each do |post| puts post.author.name end
| Pattern | Database Queries | Server Processing | Page Load Delay | Verdict |
|---|---|---|---|---|
| N+1 queries | N+1 queries (one per item) | High CPU and wait time | Delays LCP significantly | [X] Bad |
| Eager loading with includes | 2 queries (one for main, one for associations) | Low CPU and wait time | Faster LCP | [OK] Good |
posts = Post.all posts.each do |post| puts post.comments.count end
posts = Post.all posts.each do |post| puts post.comments.count end
.includes(:comments) loads all comments with posts in one query, preventing repeated queries..includes(:comments) to the query -> Option Buser.posts.comments. How can you fix this efficiently?user.posts.comments triggers queries for posts and then comments for each post, causing nested N+1 problems..includes(posts: :comments) loads users with posts and their comments in minimal queries, fixing nested N+1..includes(posts: :comments) when loading users -> Option APass the test and this pattern moves unknown