Rails ActiveRecord渴望加载需要很长时间 [英] Rails ActiveRecord Eager Load takes a long time

查看:72
本文介绍了Rails ActiveRecord渴望加载需要很长时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用紧急加载来连接两个表

I am using eager loading to join two of my tables

Model1.eager_load(:model2)

Model1表大约有800行,并且对其他表有很多引用。每当调用该行时,就需要大约3分钟来加载显示信息的视图。

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.

然后我尝试建立一个直接的Postgres连接,并运行相同的SQL查询,该查询是由急切的负载生成的,并在50ms内完成。

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.

为什么在ActiveRecord中花费那么多时间,反正我可以减少时间呢?

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

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

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


推荐答案

这很可能不是由于急于加载本身,而是反映了实例化许多模型对象的开销。从数据库检索对象时,ActiveRecord必须初始化对象。您可以通过向关联的模型添加回调来向自己证明这一点:

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.

典型的解决方案是在可能的情况下分页结果。否则,您可能需要使用原始SQL重新编写查询,以使其更具选择性。

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.

这篇关于Rails ActiveRecord渴望加载需要很长时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆