eager loading and lazy loading in rails

Eager Loading

One way to improve performance is to cut down on the number of SQL queries. You can do this through eager loading.

User.find(:all, :include => :friends)

Here you are firing only two queries :

1) One for all users.

2) One for all friends of users .

Lazy Loading :

When you have an object associated with many objects like a User has many Friends and you want to display a list as in Orkut you fire as many queries as there are friends, plus one for the object itself.

users = User.find(:all)

Then query for each user friend , like :

users.each do |user|
  friend = Friend.find_by_user_id(user.id)
end

Here

1) One query for all users.

2) N query for N no. of users friends .

Take a look on : Rails 3: Lazy loading versus eager loading

Hope that will help you to understand this .

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)