|
Posted by Surendran Sukumaran on March 17th, 2011
Eager loading loads the full objects tree that is the associated records of the objects. Consider we have two models Post and Comment and we have relation like post has many comments. Now lets find all the posts and its comments and print the post text and comment text. posts = Post.all(:limit => 20) Next we will iterate through all the post and and then get the comments for that post and print the post and comment text. posts.each do |post| puts post.post_text post.comments.each do | comment | puts comment.comment_text 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 post and N queries to find the comments for the post. Lets try to measure the time taken to execute this code using Ruby Benchmark. require 'benchmark' lazy loading = Benchmark.measure do posts = Post.all(:limit => 20) posts.each do |post| puts post.post_text post.comments.each do | comment | puts comment end end end.total puts lazy loading # Lets try to optimize the performance by trying some ways. posts = Post.includes(:comments).limit(20) posts.each do |post| puts post.post_text post.comments.each do | comment | puts comment.comment_text end end The above code fire 2 queries, one to find all the posts and the other to find the comments for the posts. Lets try to measure the time taken to execute this code using Ruby Benchmark. require 'benchmark' eager_loading = Benchmark.measure do posts = Post.includes(:comments).limit(20) posts.each do |post| puts post.post_text post.comments.each do | comment | puts comment.comment_text end end end.total puts eager_loading # The time taken in eager loading is very less compared to lazy loading, so it is good to go with eager loading when we show associations data. Tags: ActiveRecord, Eager loading, Lazy loading, Ruby, Ruby on RailsUnique Views: 7090 Total views: 7643 Follow responses at RSS 2.0. Leave a response | Trackback. One Response to “Eager loading and Lazy loading in Rails ActiveRecord”Leave a Reply |
[...] block? Maybe you just missed a place, but this is also very easy to do because of the way ActiveRecord lazily loads association content and does other kinds of database access “on [...]