Ruby On Rails Lesson
As hinted at in the last section, the feed implementation in Section 11.3.2 doesn’t scale well when the number of microposts in the feed is large, as would likely happen if a user were following, say, 5000 other users. In this section, we’ll reimplement the status feed in a way that scales better with the number of followed users.
The problem with the code in Section 11.3.2 is that
pulls all the followed users’ ids into memory and creates an array the full length of the followed users array. Since the condition in Listing 11.43 actually just checks inclusion in a set, there must be a more efficient way to do this, and indeed SQL is optimized for just such set operations. The solution involves pushing the finding of followed user ids into the database using a subselect.
We’ll start by refactoring the feed with the slightly modified code in Listing 11.44