LRU 是 Least Recently Used 的縮寫,中文為「最近最少使用」,是一種快取替換演算法。
狹義的快取指 CPU 與主存之間的快速 RAM,通常用昂貴但快速的 SRAM 而非 DRAM;廣義的快取則是兩種速度差異較大的硬體之間,用來協調傳輸速度差異的結構。除了 CPU 與主存,記憶體與硬碟之間、甚至硬碟與網路之間(例如瀏覽器快取)都有快取。
快取容量有限,一旦用滿而又有新內容要進來,就必須挑掉部分舊內容。LRU 的替換原則就是丟掉最近最少使用的那一份——譯成「最久未使用」其實更貼切,因為它每次淘汰的正是最長時間沒被碰過的資料。
典型實作是 hash map + doubly linked list。雙向鏈結串列存放資料節點,並依「最近被使用的時間」排序:一個節點被存取後,它被再次存取的機率通常更高,所以把它移到串列頭部;新插入的節點也放在頭部。這樣不斷調整,尾端自然就是最久未被使用的節點。
頭尾節點不存實際內容,僅作為哨兵:
頭 --> 結 --> 結 --> 結 --> 尾 結 點 點 點 結 點 <-- 1 <-- 2 <-- 3 <-- 點
若上圖快取已滿,要淘汰的就是節點 3。
雜湊表的作用是把「找節點」從 O(n) 降到 O(1):沒有它就得逐一走訪,有了它可以直接定位或確認不存在。
T Get(K key); void Put(K key, T data);
Get 命中時回傳資料並把該節點移到頭部;未命中則由呼叫者呼叫 Put 插入。Put 時若快取未滿,就從可用節點池取一個掛到頭部並更新雜湊表;若已滿,就把尾端的前一個節點內容換成新資料、移到頭部,並更新雜湊表。
注意:hash_map 並非 C++ 標準的一部分。以下使用 Linux 下 g++ 4.6.1,ext/hash_map 位於 /usr/include/c++/4.6/ext,需要 __gnu_cxx 命名空間;其他平台請自行確認。若已採用 C++ 11,直接用 unordered_map 即可免去這些困擾。
// A simple LRU cache written in C++
// Hash map + doubly linked list
#include <iostream>
#include <vector>
#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
template <class K, class T>
struct Node{
K key;
T data;
Node *prev, *next;
};
template <class K, class T>
class LRUCache{
public:
LRUCache(size_t size){
entries_ = new Node<K,T>[size];
for(int i=0; i<size; ++i)// 存放可用節點的地址
free_entries_.push_back(entries_+i);
head_ = new Node<K,T>;
tail_ = new Node<K,T>;
head_->prev = NULL;
head_->next = tail_;
tail_->prev = head_;
tail_->next = NULL;
}
~LRUCache(){
delete head_;
delete tail_;
delete[] entries_;
}
void Put(K key, T data){
Node<K,T> *node = hashmap_[key];
if(node){ // 節點已存在
detach(node);
node->data = data;
attach(node);
}
else{
if(free_entries_.empty()){// 無可用節點,快取已滿
node = tail_->prev;
detach(node);
hashmap_.erase(node->key);
}
else{
node = free_entries_.back();
free_entries_.pop_back();
}
node->key = key;
node->data = data;
hashmap_[key] = node;
attach(node);
}
}
T Get(K key){
Node<K,T> *node = hashmap_[key];
if(node){
detach(node);
attach(node);
return node->data;
}
else{// 快取中沒有則回傳 T 的預設值,與 hashmap 行為一致
return T();
}
}
private:
// 自串列中分離節點
void detach(Node<K,T>* node){
node->prev->next = node->next;
node->next->prev = node->prev;
}
// 將節點插入頭部
void attach(Node<K,T>* node){
node->prev = head_;
node->next = head_->next;
head_->next = node;
node->next->prev = node;
}
private:
hash_map<K, Node<K,T>* > hashmap_;
vector<Node<K,T>* > free_entries_; // 存放可用節點的地址
Node<K,T> *head_, *tail_;
Node<K,T> *entries_; // 雙向鏈結串列中的節點
};
int main(){
hash_map<int, int> map;
map[9] = 999;
cout << map[9] << endl;
cout << map[10] << endl;
LRUCache<int, string> lru_cache(100);
lru_cache.Put(1, "one");
cout << lru_cache.Get(1) << endl;
if(lru_cache.Get(2) == "")
lru_cache.Put(2, "two");
cout << lru_cache.Get(2);
return 0;
}
先用鏈結串列管理所有已使用或正在使用的節點。一開始預先配置一批節點放在 vector 中,在這些預配置節點用完之前都從 vector 取用;用完之後,就必須從串列尾端取一個節點回收再利用。若每次查找都從頭走訪效率太低,因此再用 hash_map 管理串列中的所有節點,讓查找變成 O(1)。