gpt4 book ai didi

sql - 我可以通过编写 SQL 而不是 ActiveRecord 来节省内存吗?

转载 作者:行者123 更新时间:2023-11-29 11:28:48 28 4
gpt4 key购买 nike

ActiveRecord 除了其简洁、可读的语法之外还有其他好处吗?是不是ActiveRecord比纯SQL占用内存多? (我正在使用 PostgreSQL。)

我读过 Alexander Dymo 的 blog post on Rails performance ActiveRecord 占用的内存比纯 SQL 多:

It's easy to manipulate the data with ActiveRecord. But ActiveRecord is essentially a wrapper on top of your data. If you have a 1G of data in the table, ActiveRecord representation of it will take 2G and, in some cases, more. Yes, in 90% of cases that overhead is justified by extra convenience that you get. But sometimes you don't need it.

我还阅读了 the documentation ActiveRecord 是“更好的”:

If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.

我在 Heroku 上一直遇到 Error R14 (Memory quota exceeded),所以为了解决这个问题,我了解了膨胀和内存泄漏。我已经确定了一些改进方法,包括急切加载 ActiveRecord 数据,如 List.joins(:quantities).find(@list_id),以及减少对数据库的整体调用。但我仍然渴望记忆。

如果ActiveRecord的好处只是更容易编写,那么我会尽可能地编写纯SQL。但我希望 SO 社区可以对权衡发表评论并填补我理解中的任何空白,特别是如果我在放弃 AR 之前应该三思而后行的话。

完全摆脱 AR 会很糟糕吗?

最佳答案

您需要查看该博文的下一段以获取一些上下文:

One example where you can avoid ActiveRecord's overhead is bulk updates. The code below will neither instantiate any model nor run validations and callbacks.

Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')

作者并不是说您应该使用原始 SQL 将数据(作为一堆哈希)拉入 Rails 而不是使用 ActiveRecord 将数据拉入 Rails(作为一堆模型),他们是说您不应该从数据中提取一堆数据,在 Rails 中对其进行操作,然后在可以将所有工作直接推送到数据库中时将其放回原处。

考虑以下之间的区别:

Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')

Book.where('title LIKE ?', '%Rails%').each do |b|
b.update(author: 'David')
end

第一个简单地向数据库发送一些 SQL:

update books
set author = 'David'
where title like '%Rails%'

并让数据库完成所有工作。几乎没有任何数据在数据库和您的 Rails 应用程序之间移动,您的应用程序为此几乎不使用任何内存,并且您的应用程序为此几乎不做任何工作/CPU。

第二个从数据库中拉出一堆行,创建一堆 ActiveRecord 模型,运行一堆 Ruby 代码(创建模型,设置一个值,运行验证,...),然后发送一堆单行 SQL UPDATE 返回数据库。此版本通过网络传输更多数据,在 Rails 中使用更多内存,并使用更多 CPU 来运行更多 Ruby 代码。

消息不是“不要使用 ActiveRecord”,消息是将您的数据操作逻辑放在正确的位置,而不是教条地在 Rails 中做所有事情,因为您在某处听说过“数据库中没有逻辑”。


ActiveRecord 的内存问题通常来自实例化太多模型。如果您说的是 Model.all,那么您可能做错了。如果您试图在 Rails 中同时操作多个模型,那么您可能做错了。 ORM 非常适合处理单个模型,但不适合批量操作。

如果您下拉到该博文的第 2.2 节:

Sometimes the task at hand is better done with other tools. Most commonly it's a database. Why? Because Ruby is bad at processing large data sets. Like, very very bad. Remember, Ruby takes a large memory footprint. So, for example, to process 1G of data you might need 3G and more of memory. It will take several dozen seconds to garbage collect 3G. Good database can process the data in under a second. Let me show a few examples.

你会看到博客的作者说了同样的话。

关于sql - 我可以通过编写 SQL 而不是 ActiveRecord 来节省内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882807/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com