简体   繁体   中英

Rails ActiveRecord Eager Load takes a long time

I am using eager loading to join two of my tables

Model1.eager_load(:model2)

The Model1 table has about 800 rows and has many references to other tables. Whenever that line is called, it takes about 3 minutes to load the view that shows the info.

I then tried making a straight Postgres connection and running the same SQL query that was generated from the eager load and that finished in 50ms.

Why is it taking so much longer in ActiveRecord and is there anyways I can cut down on the time?

In the console, it gets to the following SQL query (this is a simplified version, of course) and it hangs for about 3 minutes before it continues and loads the page.

SELECT model1.*, model2.* FROM model1 LEFT OUTER JOIN model2 ON model2
.foreign_key = model1.id

It's likely that this is not due to eager loading per se, but reflects the overhead of instantiating many model objects. ActiveRecord must initialize objects when retrieving them from a database. You can prove this to yourself by adding a callback to the associated model:

after_find :yodel

def yodel
  puts "Yodel-a-e-hoo!"
end

This is pretty fast, but it is not instantaneous. When you are getting back many objects, that initialization time will start to affect performance.

The typical solution is to paginate results if possible. Otherwise you may need to re-write the query, using raw SQL if necessary, to be more selective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM