Pages

Showing posts with label Eager Loading. Show all posts
Showing posts with label Eager Loading. Show all posts

Tuesday, January 17, 2017

Includes vs Joins in Rails: When and where?

The most important concept to understand when using includes and joins is they both have their optimal use cases. Includes uses eager loading whereas joins uses lazy loading, both of which are powerful but can easily be abused to reduce or overkill performance.
If we first take a look at the Ruby on Rails documentation, the most important point made in the description of the includes method is:
With includes, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
In other words, when querying a table for data with an associated table, both tables are loaded into memory which in turn reduce the amount of database queries required to retrieve any associated data. In the example below we are retrieving all companies which have an associated active Person record:

@companies = Company.includes(:persons).where(:persons => { active: true } ).all
@companies.each do |company|
     company.person.name
end

Thursday, May 2, 2013

What is eager loading?

Eager loading is a great optimization strategy to reduce the number of queries that are made against the DB.
Say you are finding 10 employees and then you are looking for their post codes. Then your query would appear something like this:
clients = Client.limit(10)
clients.each do |client|
  puts client.address.postcode
end
This may seem fine at first look but really this implementation leaves much to be desired. It makes 11 DB calls just to get the results.
Now you can optimize this query by making a slight change in the request like this:
clients = Client.includes(:address).limit(10)
clients.each do |client|
  puts client.address.postcode
end 
This new request makes two SQL calls like this:
SELECT * FROM clients LIMIT 10
SELECT addresses.* FROM addresses
    WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
So, as you can see it really loads a lot more upfront and therefore it is called eager loading.