以节省内存和性能的方式在表中查找记录和种子
我正在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过减小此数字(例如 100)并使用
find_each
遍历所有记录来减少内存中的对象数量,而不是一次获取 10000 条记录。现在一次仅获取 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.Now records will only be fetched 100 at a time, reducing the memory footprint.
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.