Eager Loading and Lazy Loading in Rails
As we know that almost every web application has an interaction with the database to fetch records or insert records and other functions.
This can be achieved through different types of queries which interact with the database and perform the desired operation.
Now when these queries are fired they take a set amount of time to run and execute and perform the needed operation. Now as a good practice and in order to improve and maximize the performance of our rails application we need to pay attention to the database access.
Reducing the number of queries made to the database can significantly speed up our rails application.
To achiever this we have a phenomenon called Eager Loading. Below is an example to explain it
Suppose you have a user table which contains a lot of users. Now along with all the users you need to fetch the friends of those users. This can be achieved in two different ways.
Rails gives us a very useful method called include which created a join in the user table and joins it with the friends table like this
class UsersController < ApplicationController
def user_friends
users = User.find(:all, :include => :friends)
end
end
When we run this method, if you check on your server log you will find that only 2 queries are fired.
- First query to fetch all the users
- Second query to fetch all the friends of these users through include.
Now this same functionality can be achieved through lazy loading as well.
class UsersController < ApplicationController
def show
users = User.all
users.each do |user|
friend = Friend.find_by(user_id:user.id)
end
end
end
On the execution of this function if we check our server log we will see that there are numerous queries.
- First query to fetch all the users
- And after that n number of queries are fired according to the number of friends of each user when it will be looping through the users object.
So this shows us the basic difference between eager loading and lazy loading and why its preferable to use eager loading over lazy loading.
0 Comment(s)