ruby - 为什么在 Ruby 中迭代需要这么长时间?
问题描述
嘿,我是 Ruby 的新手,我有一个问题。我的文件 Wordlist 有超过 100.000 个单词,我想使用 test_password 方法检查我的哈希码是否等于文件 Wordlist 中的一个单词,但是当我检查文件的最后一个单词时,它需要很长时间才能遍历它,请有人帮助我如何使它更快?
File.open("Wordlist.txt", "r") do |fi|
fi.each_line do |words|
text_word << words.chomp
end
end
text_word.each do |words|
if test_password(words,ARGV[0])
puts "FOUND: " + words
break
end
end
解决方案
你可以创建一个带有[hash_code(word), word]
对的散列,然后将结果写成 JSON、YAML 或数据库(例如 SQLite)。如果需要很长时间来计算这个哈希值也没关系,因为你只需要做一次。下一次,您只需要读取保存的哈希值,这应该很快。
现在,检查一个单词或一个哈希码是否在哈希内应该非常快。
这是一个留给你的 TODO 的小例子:
require 'json'
require 'digest/md5'
hashcodes = {}
def my_hashcode(word)
Digest::MD5.hexdigest word
end
# This part is slow, that's okay because it can be saved once and for all and doesn't depend on your input
File.open('/usr/share/dict/american-english') do |wordlist|
wordlist.each do |word|
word.chomp!
hashcodes[my_hashcode(word)] = word
end
end
#TODO: Write hashcodes to JSON file
#TODO: Read hashcode from JSON file
# This part depends on your input but is very fast:
some_hashcode = my_hashcode("test")
p hashcodes[some_hashcode]
# => "test"
p hashcodes["S0MEWEIRDH4SH"]
# => nil
推荐阅读
- android-studio - 如何在资源布局 xml 文件的组件树中启用/显示设备屏幕?
- ios - 如何在 wkwebview 中打开“window.open”
- java - 我如何测试保存方法?
- jquery - 为什么 select2 没有用最新数据填充控件?
- javascript - Terser 不提供缩小文件
- python - 将字典中的键与字符串匹配。而不是循环字典或字符串单词中的键
- c# - 实数的四舍五入
- angular - 在Angular 7中重用它们时如何将参数传递给其他组件
- c - printf("%s",*&*str); 的输出是什么?str 在哪里是指针?
- javascript - 中继器问题中的 Javascript“阅读更多”