结合两个数组的Ruby会导致进程耗尽内存

时间:2014-08-13 19:48:31

标签: ruby arrays out-of-memory ruby-2.1

将两个具有100k项目的哈希数组合在一起会导致在2GB VM上运行的进程耗尽内存。我无法理解如何/为什么。

假设我有一个像这样的哈希,我用50个键/值对填充它。

h = {}
1..50.times{ h[SecureRandom.hex] = SecureRandom.hex}

我将100k h放入两个数组:

a = []
a1 = []
1..100_000.times{ a << h }
1..100_000.times{ a1 << h }

当我尝试将a1添加到a时,IRB内存不足:

2.1.1 :008 > a << a1
NoMemoryError: failed to allocate memory

这两个阵列真的太大而无法在内存中组合吗?实现这一目标的首选方法是什么?

我正在运行ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-linux]并且VM上没有运行其他进程。

1 个答案:

答案 0 :(得分:6)

问题很可能不是Ru​​by在执行此操作时耗尽内存(特别是因为h哈希只有一个副本),而是在尝试显示时IRB内存不足结果。尝试在IRB的最后一行之后添加; nil;这应该解决问题,因为它会阻止IRB尝试显示结果哈希。

示例:

require 'securerandom'
require 'objspace'

h = {}
1..50.times{ h[SecureRandom.hex] = SecureRandom.hex}
a = []
a1 = []
1..100_000.times{ a << h }
1..100_000.times{ a1 << h }
a << a1; nil # Semicolon and nil are for IRB, not needed with regular Ruby

puts "Total memory usage: #{ObjectSpace.memsize_of_all/1000.0} KB"

我得到Total memory usage: 7526.543 KB的结果;没有接近2 GB的地方。