5. Here’s what happens...
Database is
queried for
parent record
App needs info
about child
records
Database is
queried once per
child record
6. Products and users:
×An product index page asks for info
about some products...
×Then needs to load info about the
product creator…
×...querying the database for each
creator.
8. What if you’re making 100s, 1000s,
10000(...)’s requests?
What if your server is far away?
If it takes 1ms to make 1 request, 2ms for 2...
Those numbers compound painfully.
Because it slows pages down.
9. What would be faster?
Making 1 query with 100 results
instead of
100 queries with 1 result each.
11. Your Rails tools
:preload
:includes
:eager_load
Pre-make aggregate database
queries for the resource you
need
Post.preload(:user)
Associations
Pre-make an association for the
resource you’ll need in order to
preload it
has_one :latest_post,
-> { order(created_at: :desc).limit(1) },
class_name: "Post"
12. “Try the Bullet gem, too:
It informs you of n+1 errors via excellent
logging capability.
This can become a huge problem, especially if your server is far away from the requesting client. If it takes 1ms to process a single request, think of how that gets compounded when you’re making hundreds, thousands, or more requests at the same time. This is why N+1 errors are considered one of the common reasons for slow page loads.
This can become a huge problem, especially if your server is far away from the requesting client. If it takes 1ms to process a single request, think of how that gets compounded when you’re making hundreds, thousands, or more requests at the same time. This is why N+1 errors are considered one of the common reasons for slow page loads.