How do you refresh a cache key's recency after a hit?

OrderedDict.move_to_end repositions an existing key while retaining the associated value.

Python example and interpretation

Starting with A,B,C, move a hit on A to the tail and B becomes the next eviction candidate. A read must trigger the move explicitly.

from collections import OrderedDict
q=OrderedDict.fromkeys('ABC')
q.move_to_end('A')
[list(q),q.popitem(last=False)[0]]

Result [['B', 'C', 'A'], 'B']

中文

缓存命中后如何更新最近使用顺序?

OrderedDict.move_to_end 可重新安排已有键的位置,同时保留其关联值。

Python 算例与适用条件

缓存顺序原为 A、B、C,访问 A 后移至末尾,下一次按最早顺序淘汰的是 B。需要主动调用才能记录命中。

from collections import OrderedDict
q=OrderedDict.fromkeys('ABC')
q.move_to_end('A')
[list(q),q.popitem(last=False)[0]]

结果 [['B', 'C', 'A'], 'B']

References / 参考来源

Keep reading / 继续阅读