[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
Ruby problem ⑦
Rails N + 1 problem countermeasure includes, preload, eager_load
ruby search problem
[Ruby] FizzBuzz problem
ruby API problem
scan method problem
[Java] Problem No. 2
[Java] Problem No.3
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