LRU(Least Recently Used, 최근 최소 사용) cache는 용량에 도달하면 가장 오랫동안 접근되지 않은 항목을 축출합니다. 고전적인 설계는 hash map(O(1) 조회)과 doubly linked list(O(1) 재정렬)를 결합하여 O(1) get과 put을 제공합니다.
두 구조 설계
text
HashMap: key -> node DLL (최근성 순서):
MRU <-> ... <-> LRU
get/put: map이 O(1)에 접근된 노드를 앞(MRU)으로 이동
노드를 찾음; DLL이 O(1)에 가득 차면 tail(LRU)을 축출
앞으로 splice함
코드
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=)
