Ruby 循环中的代码内存泄漏
Ruby code memory leak in loop
以下代码存在内存泄漏。 运行ning 在 ruby 2.1.1 下。我找不到实际的泄漏。
q = Queue.new("test")
while true do
m = q.dequeue
body = JSON.parse(m.body)
user_id = body["Records"][0]
user = V2::User.find(user_id)
post = V2::Post.find(post_id)
end
运行几个小时后,我添加了GC.start,但它没有解决问题
q = Queue.new("test")
while true do
m = q.dequeue
body = JSON.parse(m.body)
user_id = body["Records"][0]
user = V2::User.find(user_id)
post = V2::Post.find(post_id)
GC.start
end
我不知道如何找到实际的内存泄漏。
尝试从下往上删除这些行,看看内存泄漏是否仍然存在。内存泄漏可能来自 find 方法,或者可能来自 JSON.parse(极不可能),或者自定义 Queue 数据结构。如果在删除所有行后内存泄漏仍然存在,则可能来自工作人员本身 and/or 程序 运行 工作人员。
q = Queue.new("test")
while true do
m = q.dequeue # Finally remove this and stub the while true with a sleep or something
body = JSON.parse(m.body) # Then remove these two lines
user_id = body["Records"][0]
user = V2::User.find(user_id) # Remove the bottom two lines first
post = V2::Post.find(post_id)
end
我敢打赌问题出在引入的局部变量(原文如此!)。摆脱 user_id
和 post_id
,它可能会停止泄漏:
# user_id = body["Records"][0]
# user = V2::User.find(user_id)
user = V2::User.find(body["Records"][0]) # sic!
原因是怎样 Ruby stores objects in RValues.
以下代码存在内存泄漏。 运行ning 在 ruby 2.1.1 下。我找不到实际的泄漏。
q = Queue.new("test")
while true do
m = q.dequeue
body = JSON.parse(m.body)
user_id = body["Records"][0]
user = V2::User.find(user_id)
post = V2::Post.find(post_id)
end
运行几个小时后,我添加了GC.start,但它没有解决问题
q = Queue.new("test")
while true do
m = q.dequeue
body = JSON.parse(m.body)
user_id = body["Records"][0]
user = V2::User.find(user_id)
post = V2::Post.find(post_id)
GC.start
end
我不知道如何找到实际的内存泄漏。
尝试从下往上删除这些行,看看内存泄漏是否仍然存在。内存泄漏可能来自 find 方法,或者可能来自 JSON.parse(极不可能),或者自定义 Queue 数据结构。如果在删除所有行后内存泄漏仍然存在,则可能来自工作人员本身 and/or 程序 运行 工作人员。
q = Queue.new("test")
while true do
m = q.dequeue # Finally remove this and stub the while true with a sleep or something
body = JSON.parse(m.body) # Then remove these two lines
user_id = body["Records"][0]
user = V2::User.find(user_id) # Remove the bottom two lines first
post = V2::Post.find(post_id)
end
我敢打赌问题出在引入的局部变量(原文如此!)。摆脱 user_id
和 post_id
,它可能会停止泄漏:
# user_id = body["Records"][0]
# user = V2::User.find(user_id)
user = V2::User.find(body["Records"][0]) # sic!
原因是怎样 Ruby stores objects in RValues.