gpt4 book ai didi

Ruby 内存管理

转载 作者:IT王子 更新时间:2023-10-28 23:29:18 26 4
gpt4 key购买 nike

我使用 Ruby 已经有一段时间了,我发现对于更大的项目,它会占用相当多的内存。在 Ruby 中减少内存使用的最佳实践是什么?

  • 请让每个答案都有一个“最佳实践”,并让社区投票。

最佳答案

在处理大量 ActiveRecord 对象时要非常小心...在循环中处理这些对象时,如果在每次迭代中您都使用 ActiveRecord 的 has_many、belongs_to 等加载它们的相关对象 - 内存使用量会增长很多,因为属于数组的每个对象都会增长...

以下技术对我们帮助很大(简化示例):

students.each do |student|
cloned_student = student.clone
...
cloned_student.books.detect {...}
ca_teachers = cloned_student.teachers.detect {|teacher| teacher.address.state == 'CA'}
ca_teachers.blah_blah
...
# Not sure if the following is necessary, but we have it just in case...
cloned_student = nil
end

在上面的代码中,“cloned_student”是增长的对象,但由于它在每次迭代结束时“无效”,这对于大量学生来说不是问题。如果我们不做“克隆”,循环变量“学生”会增长,但由于它属于一个数组 - 只要数组对象存在,它所使用的内存就永远不会释放。

不同的方法也可以:

students.each do |student|
loop_student = Student.find(student.id) # just re-find the record into local variable.
...
loop_student.books.detect {...}
ca_teachers = loop_student.teachers.detect {|teacher| teacher.address.state == 'CA'}
ca_teachers.blah_blah
...
end

在我们的生产环境中,我们有一个后台进程无法完成一次,因为 8Gb 的 RAM 还不够。在这个小改动之后,它使用不到 1Gb 来处理相同数量的数据......

关于Ruby 内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/181406/

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