我是一名 Ruby 新手(使用的是 1.9.1 版本),希望能得到帮助。我通过谷歌学到了关于 Ruby 的一切。我正在尝试比较两个哈希数组,但由于它们的大小,这个过程太慢了,而且很容易耗尽内存。如果有任何帮助,将不胜感激。
我有一个类(ParseCSV),其中包含多个方法(initialize、open、compare、strip、output)。目前的工作方式如下(并且已经通过我编写的测试,只是使用了更小的数据集):
我有一个类(ParseCSV),其中包含多个方法(initialize、open、compare、strip、output)。目前的工作方式如下(并且已经通过我编写的测试,只是使用了更小的数据集):
file1 = ParseCSV.new(“some_file”)
file2 = ParseCSV.new(“some_other_file”)
file1.open #this reads the file contents into an Array of Hash’s through the CSV library
file1.strip #This is just removing extra hash’s from each array index. So normally there are fifty hash’s in each array index, this is just done to help reduce memory consumption.
file2.open
file2.compare(“file1.storage”) #@storage is The array of hash’s from the open method
file2.output
现在我遇到的问题是比较方法。在处理小数据集时,这并不是什么大问题,速度足够快。然而,在这种情况下,我正在将约400,000条记录(全部读入哈希数组)与大约450,000条记录的一个文件进行比较。我正在尝试加快速度。另外,我无法对file2运行strip方法。以下是我目前的做法:
def compare(x)
#obviously just a verbose message
puts "Comparing and leaving behind non matching entries"
x.each do |row|
#@storage is the array of hashes
@storage.each_index do |y|
if row[@opts[:field]] == @storage[y][@opts[:field]]
@storage.delete_at(y)
end
end
end
end
希望这样说得通。我知道这将是一个缓慢的过程,因为它必须迭代400,000行440,000次。但是您有没有其他想法来加速并可能减少内存消耗?
Set
只是一个Hash
(如果你查看实现,你会发现Set
类只是将委托给一个Hash
,其中Hash
键是Set
值,而Hash
值都是true
)。而且我非常确定(事实上,我在两天前回答另一个问题时证明了这一点),你提到的错误已经在Ruby 1.9中修复。我刚刚重新测试了一下,它确实似乎可以工作。 - Jörg W Mittag