我正在使用ruby将大型TXT文件加载到数组或哈希中.输入文件包含超过1'000'000个MD5哈希值,按字母顺序排序,不重复.
Ruby中最快的方法是找出我的数组或哈希中是否存在某个哈希值?目前我使用数组并"包含?".
def loadhashlist
@all_hash_values = Array.new
f = File.readlines("inputmd5.txt").each do |row|
@all_hash_values.push(row.gsub("\n",""))
end
end
loadhashlist
def hashlookup(file)
md5 = file.getMd5
if @all_hash_values.include? md5
#code goes here
end
end
Run Code Online (Sandbox Code Playgroud)
是的,你可以使用一个最多的数组,O(logN)但是使用一个集合更快,语义更好.
require 'set'
hashes = Set.new
hashes << 'foo'
hashes << 'bar'
hashes.include?('bar') # => true
Run Code Online (Sandbox Code Playgroud)
在ruby集中使用哈希表实现,因此查找是O(1).