LRU (Least Recently Used) 缓存在达到容量时会驱逐最长时间未被访问的项。经典设计将哈希映射(O(1) 查找)与双向链表(O(1) 重新排序)结合起来,提供 O(1) get 和 put。
两个结构的设计
text
HashMap: key -> node DLL (recency order):
MRU <-> ... <-> LRU
get/put: map finds node move touched node to front (MRU)
in O(1); DLL splices it evict the tail (LRU) when full
to the front in O(1)
Code
python
collections OrderedDict
:
():
.cap = capacity
.cache = OrderedDict()
():
key .cache:
-
.cache.move_to_end(key)
.cache[key]
():
key .cache:
.cache.move_to_end(key)
.cache[key] = value
(.cache) > .cap:
.cache.popitem(last=)
