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

use*_*752 1 ruby arrays out-of-memory ruby-2.1

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

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

h = {}
1..50.times{ h[SecureRandom.hex] = SecureRandom.hex}
Run Code Online (Sandbox Code Playgroud)

我将100k hs放入两个数组中,如下所示:

a = []
a1 = []
1..100_000.times{ a << h }
1..100_000.times{ a1 << h }
Run Code Online (Sandbox Code Playgroud)

当我尝试添加a1a,IRB内存用完:

2.1.1 :008 > a << a1
NoMemoryError: failed to allocate memory
Run Code Online (Sandbox Code Playgroud)

两个阵列真的太大而无法在内存中组合吗?完成此任务的首选方法是什么?

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

Aje*_*i32 6

问题很可能不是Ru​​by在执行此操作时耗尽内存(特别是因为只有一个h哈希副本),而是在尝试显示结果时IRB内存不足.尝试; nil在IRB的最后一行之后添加一个; 这应该解决问题,因为它会阻止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"
Run Code Online (Sandbox Code Playgroud)

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