Rails ActiveRecord Eager Load takes a long time

巧了我就是萌 提交于 2019-12-13 04:58:13

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/24762549/rails-activerecord-eager-load-takes-a-long-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!