我们的程序创建一个主散列,其中每个键都是表示ID(大约10-20个字符)的符号。每个值都是一个空的散列。Ruby中的内存使用率高:500B正常的空散列?
主散列有大约800K条记录。
但是我们看到ruby的内存几乎达到了400MB。
这表明每个键/值对(符号+空哈希)每个消耗约500B。
这是正常的红宝石?下面
代码:
def load_app_ids
cols = get_columns AppFile
id_col = cols[:application_id]
each_record AppFile do |r|
@apps[r[id_col].intern] = {}
end
end
# Takes a line, strips the record seperator, and return
# an array of fields
def split_line(line)
line.gsub(RecordSeperator, "").split(FieldSeperator)
end
# Run a block on each record in a file, up to
# @limit records
def each_record(filename, &block)
i = 0
path = File.join(@dir, filename)
File.open(path, "r").each_line(RecordSeperator) do |line|
# Get the line split into columns unless it is
# a comment
block.call split_line(line) unless line =~ /^#/
# This import can take a loooong time.
print "\r#{i}" if (i+=1) % 1000 == 0
break if @limit and i >= @limit
end
print "\n" if i > 1000
end
# Return map of column name symbols to column number
def get_columns(filename)
path = File.join(@dir, filename)
description = split_line(File.open(path, &:readline))
# Strip the leading comment character
description[0].gsub!(/^#/, "")
# Return map of symbol to column number
Hash[ description.map { |str| [ str.intern, description.index(str) ] } ]
end
哈希不是内存中唯一的东西,是吗? – 2013-03-19 05:14:02
我们正在阅读文件的每一行,将尽快发布代码。谢谢。 – Crashalot 2013-03-19 05:42:37
更新了代码 – Crashalot 2013-03-19 06:35:59