简洁高效的LRU Map C++实现

LRU是缓存替换的一个重要原则。其思想可以广泛的应用于很多场合。通过维护一个Key和Timestamp之间的双向映射,可以实现一个简洁高效的通用LRU Map。

   1: #include <map>
   2: #include <string>
   3: #include <iostream>
   4: using namespace std;
   5:  
   6:  template<class K, class V>
   7:  struct lrumap:public map<K, V> 
   8:  {
   9:      typedef map<K, V> base_type;
  10:      typedef size_t timestamp;
  11:      typedef typename map<K, timestamp> K2T;
  12:      typedef typename map<timestamp, K> T2K;
  13:   
  14:      K2T k2t; // from key to timestamp
  15:      T2K t2k; // from timestamp to key
  16:   
  17:      timestamp tm;
  18:      size_type capacity;
  19:      lrumap(size_type cap=10)
  20:          : tm(1), capacity(cap) {}
  21:   
  22:      V& operator[](const K& k)
  23:      {
  24:          timestamp& _tm=k2t[k];
  25:          if(_tm) // if the timestamp already exist, delete it from t2k
  26:              t2k.erase(_tm);
  27:          _tm=tm++; // update timestamp in k2t
  28:          t2k[_tm]=k; // update key in t2k
  29:   
  30:          V& ret= base_type::operator[](k);
  31:   
  32:          // remove the oldest if necessary
  33:          if(size()>capacity)
  34:          {
  35:              K k=t2k.begin()->second; // get the eldest key
  36:              erase(k);
  37:          }
  38:          return ret;
  39:      }
  40:      void erase(const K& k)
  41:      {
  42:          // erase timestamp <-> key reference
  43:          t2k.erase(k2t[k]);
  44:          k2t.erase(k);
  45:          // then the actual data
  46:          base_type::erase(k);
  47:      }
  48:  };

在这个实现中,当lrumap增长到等于capacity时,会出现频繁的在map中插入/删除节点的情况。大量的动态内存分配/释放会严重影响程序性能。配合pool_allocator会大大的提高这个LRU map的性能,使其成为一个真正有用的LRU map。

posted on 2009-09-29 13:36  Tactoth  阅读(2656)  评论(0编辑  收藏  举报

导航