以节省内存和性能的方式在表中查找记录和种子

发布于 2024-11-08 11:14:05 字数 529 浏览 0 评论 0原文

我正在 Rails 2.3.11 环境中工作。

我想像这样创建一个 Social_activities 表:

votes = Vote.find(:all, :limit => 10000, :order => 'created_at DESC')
for vote in votes do
  act = vote.activity_for!
  act.created_at = vote.created_at
  act.save!
end

comments = Comment.find(:all, :limit => 10000, :order => 'created_at DESC')
for comment in comments do
  act = comment.activity_for!
  act.created_at = comment.created_at
  act.save!
end

...等等...

如您所见,我正在处理很多记录。我怎样才能以最节省内存和性能的方式做到这一点?

I'm working in Rails 2.3.11 environment.

I want to seed a social_activities table like so:

votes = Vote.find(:all, :limit => 10000, :order => 'created_at DESC')
for vote in votes do
  act = vote.activity_for!
  act.created_at = vote.created_at
  act.save!
end

comments = Comment.find(:all, :limit => 10000, :order => 'created_at DESC')
for comment in comments do
  act = comment.activity_for!
  act.created_at = comment.created_at
  act.save!
end

...and...so on...

As you can see, I'm processing a lot of records. How can I do so in the most memory- and performance-efficient way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花开柳相依 2024-11-15 11:14:05

您可以通过减小此数字(例如 100)并使用 find_each 遍历所有记录来减少内存中的对象数量,而不是一次获取 10000 条记录。

Vote.find_each(:order => 'created_at DESC', :batch_size => 100) do |vote|
  act = vote.activity_for!
  act.created_at = vote.created_at
  act.save!
end

Comment.find_each(:order => 'created_at DESC', :batch_size => 100) do |comment|
  act = comment.activity_for!
  act.created_at = comment.created_at
  act.save!
end

现在一次仅获取 100 条记录,从而减少了内存占用。

Instead of fetching 10000 records at a time, you can reduce the number of objects in memory by making this number smaller (say 100), and using find_each to work your way through all the records.

Vote.find_each(:order => 'created_at DESC', :batch_size => 100) do |vote|
  act = vote.activity_for!
  act.created_at = vote.created_at
  act.save!
end

Comment.find_each(:order => 'created_at DESC', :batch_size => 100) do |comment|
  act = comment.activity_for!
  act.created_at = comment.created_at
  act.save!
end

Now records will only be fetched 100 at a time, reducing the memory footprint.

⊕婉儿 2024-11-15 11:14:05

Active Record 不太适合导入或移动大型数据集。这看起来像是您应该直接使用 SQL 语句执行的操作。

在 SQL 中,我认为您可以通过内部联接或类似的更新来完成此操作。无论哪种方式,SQL 服务器都会直接运行您的查询,这比 Active Record 快得多。

Active Record isn't great for importing or moving large datasets around. This looks like something you should do with an SQL statement directly.

In SQL I think you would do this with an update across an inner join or something similiar. Either way the SQL server would run your query directly, and this would be dramatically faster than Active Record.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文