简体   繁体   English

Rails ActiveRecord渴望加载需要很长时间

[英]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. Model1表大约有800行,并且对其他表有很多引用。 Whenever that line is called, it takes about 3 minutes to load the view that shows the info. 每当调用该行时,就需要大约3分钟来加载显示信息的视图。

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. 然后,我尝试建立直接的Postgres连接,并运行相同的SQL查询,该查询是由急切的负载生成的,并在50ms内完成。

Why is it taking so much longer in ActiveRecord and is there anyways I can cut down on the time? 为什么在ActiveRecord中花费的时间这么长,并且我还能减少时间吗?

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. 在控制台中,它进入以下SQL查询(当然,这是简化版本),并且挂起大约3分钟,然后继续并加载页面。

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. 从数据库检索对象时,ActiveRecord必须初始化对象。 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. 否则,您可能需要使用原始SQL重新编写查询,以便更具选择性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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