<p>为什么不做基准测试呢?</p>
<pre><code>>>> def sha1(s):
... return hashlib.sha1(s).hexdigest()
...
>>> def sha512(s):
... return hashlib.sha512(s).hexdigest()
...
>>> t1 = timeit.Timer("sha1('asdf' * 100)", "from __main__ import sha1")
>>> t512 = timeit.Timer("sha512('asdf' * 100)", "from __main__ import sha512")
>>> t1.timeit()
3.2463729381561279
>>> t512.timeit()
6.5079669952392578
</code></pre>
<p>所以在我的机器上,<code>hash512</code>的速度是<code>sha1</code>的两倍。但正如<a href="https://stackoverflow.com/users/238704/gregs">GregS</a>所说,为什么要使用安全哈希进行缓存?请尝试内置哈希算法,该算法应该非常快速并经过调整:</p>
<pre><code>>>> s = "asdf"
>>> hash(s)
-618826466
>>> s = "xxx"
>>> hash(s)
943435
>>> hash("xxx")
943435
</code></pre>
<p>或者更好的是,使用内置的Python字典。也许你可以告诉我们更多关于缓存的计划。</p>
<p><em>编辑:</em>
我想你是想达到这样的目的:</p>
<pre><code>hash = hashlib.sha1(object_to_cache_as_string).hexdigest()
cache[hash] = object_to_cache
</code></pre>
<p>我刚才提到的“使用内置Python词汇表”是,您可以简化上面的内容:</p>
<pre><code>cache[object_to_cache_as_string] = object_to_cache
</code></pre>
<p>以这种方式,Python负责散列,所以您不必这样做!</p>
<p>关于您的特定问题,您可以参考<a href="https://stackoverflow.com/questions/1151658/python-hashable-dicts">Python hashable dicts</a>,以便使字典可散列化。然后,缓存对象所需做的就是:</p>
<pre><code>cache[object_to_cache] = object_to_cache
</code></pre>