我经常需要相对较小的(< 10000条目< 1kb)缓存来加速计算。我通常的代码如下所示:什么是小而简单的缓存的最佳数据结构
cache = {}
def calculate_caches(parms):
if parms not in cache:
cache[parms] = calculate(parms)
return cache[parms]
工作正常,但对于长时间运行的进程我害怕内存泄漏。所以,我经常实施蛮力记忆夹紧这样的:
if len(cache) > 1000:
cache = {}
合理运作良好,在大多数情况下,仍然是干净,简单的代码。但是,如果我想要一个真正的LRU strategy我需要时间戳和缓存条目。使用字典的问题是,现在缓存过期意味着遍历整个缓存,既不优雅也不高效。
cache = {}
def calculate_caches(parms):
if parms not in cache:
cache[parms] = (time.time(), calculate(parms))
expire()
return cache[parms][1]
def expire()
if len(cache) > 1000:
mintime = time.time()
time2key = {}
for key, (timestamp, val) in cache.items():
mintime = min([mintime, timestamp])
time2key[timestamp] = key
if mintime in time2key:
del cache[time2key[mintime]]
是否有优选的方法/数据结构来实现临时缓存?
我的问题与this question很相似,但我不需要列表按时间排序,我不希望被骗。