生产代码中的 LRU 实现

新手上路,请多包涵

我有一些 C++ 代码需要使用 LRU 技术实现缓存替换。

到目前为止,我知道两种实现 LRU 缓存替换的方法:

  1. 每次访问缓存数据时使用timeStamp,最后比较替换时的timeStamps。
  2. 使用一堆缓存项,如果最近访问它们,则将它们移动到顶部,因此最后底部将包含 LRU Candidate。

那么,其中哪一个更适合用于生产代码?

他们还有其他更好的方法吗?

原文由 sud03r 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 675
2 个回答

最近,我使用散列映射上的链表实现了 LRU 缓存。

     /// Typedef for URL/Entry pair
    typedef std::pair< std::string, Entry > EntryPair;

    /// Typedef for Cache list
    typedef std::list< EntryPair > CacheList;

    /// Typedef for URL-indexed map into the CacheList
    typedef boost::unordered_map< std::string, CacheList::iterator > CacheMap;

    /// Cache LRU list
    CacheList mCacheList;

    /// Cache map into the list
    CacheMap mCacheMap;

它的优点是对于所有重要操作都是 O(1)。

插入算法:

 // create new entry
Entry iEntry( ... );

// push it to the front;
mCacheList.push_front( std::make_pair( aURL, iEntry ) );

// add it to the cache map
mCacheMap[ aURL ] = mCacheList.begin();

// increase count of entries
mEntries++;

// check if it's time to remove the last element
if ( mEntries > mMaxEntries )
{
    // erease from the map the last cache list element
    mCacheMap.erase( mCacheList.back().first );

    // erase it from the list
    mCacheList.pop_back();

    // decrease count
    mEntries--;
}

原文由 Kornel Kisielewicz 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题