1

组合两个具有 100k 项的哈希数组会导致在 2GB 虚拟机上运行的进程耗尽内存。我不明白如何/为什么。

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

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

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

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

当我尝试添加时a1aIRB 内存不足:

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

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

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

4

1 回答 1

6

问题很可能不是 Ruby 在执行此操作时内存不足(特别是因为只有一个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"

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

于 2014-08-13T20:12:45.170 回答