Limits of hashes comparisons
<p>I'm storing hash codes in a file, one hash per line.</p>

<p>When I have a new hash code, I open the file and check if
the hash code already exists and if it doesn't exist,
I save it to that file.</p>

<pre><code>f = open("hashes.txt", "w")
hashes = f.readlines()
hash_code = "ff071fdf1e060400"
if not hash_code in hashes:
  hashes.append(hash_code)
for h in hashes:
  f.write(h)
f.close()
</code></pre>

<p>This code may be slow, when the number of lines in hashes.txt grows.
Is there some better storage mechanism and check to make it faster
in that case? I need fastest possible check (within a few seconds).</p>

<p>I would do this:</p>

<pre><code>class Hashes(object):
    def __init__(self, filename):
        self.filename = filename
        with open(filename, 'rt') as f:             # read the file only once
            self.hashes = set(line.strip() for line in f)

    def add_hash(self, hash):
        if hash not in self.hashes:                 # this is very fast with sets
            self.hashes.add(hash)
            with open(self.filename, 'at') as f:
                print(hash, file=f)                 # write only one hash

hashes = Hashes("hashes.txt")
hashes.add_hash("ff071fdf1e060400")
</code></pre>

<p>Because:</p>

<ul>
<li>the file is read only once</li>
<li>checking whether a hash exists is very fast with sets (no need to read all of them)</li>
<li>hashes are added by writing only the new hash</li>
<li>the class simplifies creation of mutiple hash files and cleanup of cached hashes, and it simplifies maintenance by organising the code</li>
</ul>

<p>The downside is that all hashes are kept in memory. If there are many millions of hashes, that could start causing problems, but until then it is fine. It is better than fine, if speed is important.</p>

python hash