[N + 1 problem]

What is the N + 1 problem?

A problem that occurs when models are associated with each other in an association.

For example, when a user and a post are linked in an app such as Twitter When listing posts on the top page, if you access the database every time to search for the user associated with each post, the performance of the application will decrease.

If you have 10,000 posts, you have to access the database 10,000 times.

This problem is called the N + 1 problem.

The method to solve this problem

include method

The method called.

This method accessed the database every time and searched for the associated data. It gets all the data at once.

Therefore, even if there are 10,000 posts, you only need to access the database once.

n+1.png

As shown in the image above, you can use it by setting includes (: associated model) in the processing content of the index action.

With this, no matter how many posts are added when listing tweets etc., performance will not be reduced.

Recommended Posts

[N + 1 problem]
Don't underestimate the N + 1 problem!
FizzBuzz problem
Christmas N + 1
Ruby problem ⑦
ruby search problem
[Ruby] FizzBuzz problem
ruby API problem
[Ruby] FizzBuzz problem
scan method problem
Google recruit problem
[Java] Problem No. 2
[Java] Problem No.3
[Ruby] Ruby API problem
ruby API problem
[Java] Problem No.1
Ruby_work basic problem
/ n \ n docker java
[Beginner] Discover the N + 1 problem! How to use Bullet
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on