算法LRU、LFU与FIFO

缓存过期管理有很多种方式,常见的有FIFO,LRU与LFU,当然还有其他算法,比如rand,opt等。这三种简单的区别如下:

FIFO:是first in first out 的缩写
LRU :是least recently used 的缩写
LFU :是least frequently used 的缩写

fifo很容易理解,是先进先出,最做进去的page将被置换
lru是最近最少使用的page将被置换
lfu是最近最不常用的page将被置换

Least Recently Used (LRU)
Discards the least recently used items first. This algorithm requires keeping track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping "age bits" for cache-lines and track the "Least Recently Used" cache-line based on age-bits. In such an implementation, every time a cache-line is used, the age of all other cache-lines changes.


Least-Frequently Used (LFU)
Counts how often an item is needed. Those that are used least often are discarded first.


It requires three data structures. One is a hash table which is used to cache the key/values so that given a key we can retrieve the cache entry at O(1). Second one is a double linked list for each frequency of access. The max frequency is capped at the cache size to avoid creating more and more frequency list entries. If we have a cache of max size 4 then we will end up with 4 different frequencies. Each frequency will have a double linked list to keep track of the cache entries belonging to that particular frequency. The third data structure would be to somehow link these frequencies lists. It can be either an array or another linked list so that on accessing a cache entry it can be easily promoted to the next frequency list in time O(1).

redis使用LRU的近似算法来进行page置换
LRU的一个例子:
1 2 3 4 1 2 5 1 2 3 4 5
1 1 1 1 1 1 1 1 1 1 1 5

2 2 2 2 2 2 2 2 2 2 2


3 3 3 3 5 5 5 5 3 3



4 4 4 4 4 4 3 4 4
fill fill fill full hit hit repl hit hit repl repl repl



参考:
1.http://en.wikipedia.org/wiki/Cache_algorithms
2.http://stackoverflow.com/questions/17759560/what-is-the-difference-between-lru-and-lfu 3.http://redis.io/topics/lru-cache
4.http://www.cs.jhu.edu/~yairamir/cs418/os6/sld014.htm

你可能感兴趣的:(算法LRU、LFU与FIFO)