我们的程序创建了一个主哈希,其中每个键都是一个代表 ID 的符号(大约 10-20 个字符)。每个值都是一个空哈希。
主哈希有大约 80 万条记录。
然而,我们看到 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