Eager loading


Eager loading is one of the basic features of Rails but when it’s missing or misused it can lead to huge performance hits because of lazy loading(Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. The opposite of lazy loading is eager loading.)

Eager loading loads the full objects tree that is the associated records of the objects. When you load records from the database and also want to access the associated objects for each of these records, it’s a good idea to make use of eager loading. Eager loading reduces the amount of queries made to the database and therefor increases performance.

To make use of eager loading, you can use the :include parameter (Rails 2) or the includes method (Rails 3) respectively when doing your ActiveRecord finds.

Consider we have two models Challenge and Task and we have relation like Challenge has many tasks.

Challenge model has the relation has_many :tasks
Task model has the relation belongs_to :challenge

Now lets find all the challenge and its tasks and print the challenge name and task name.

challenges = Challenge.all(:limit => 10)

Next we will iterate through all the challenge and and then get the tasks for that challenge and print the challenge and task name.

challenges.each do |each_challenge|
    puts each_challenge.name
   each_challenge.tasks.each do | each_task |
      puts each_task.name
   end
end

Okay this code works fine, nothing wrong but there is performance issue in this code,
it fires 1 query to find all the challenge and N queries to find the tasks for the challenge.

We can use the includes method provided by Active Record that loads the full objects tree that is the associated records of the objects.

challenges = Challenge.includes(:tasks).limit(10)

challenges.each do |each_challenge|
   puts each_challenge.name
     each_challenge.tasks.each do | each_task |
        puts each_task.name
     end
end

The above code fire 2 queries, one to find all the challenges and the other to find the tasks for the challenges.
This concept is called eager loading, so the challenges variable contains all the challenges and the associated tasks.

That’s it…!!!

Cheers…!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s