Is it there any LRU implementation of IDictionary?

前端 未结 10 1788
走了就别回头了
走了就别回头了 2020-11-29 21:20

I would like to implement a simple in-memory LRU cache system and I was thinking about a solution based on an IDictionary implementation which could handle an hashed LRU mec

10条回答
  •  孤城傲影
    2020-11-29 21:38

    This a very simple and fast implementation we developed for a web site we own.

    We tried to improve the code as much as possible, while keeping it thread safe. I think the code is very simple and clear, but if you need some explanation or a guide related to how to use it, don't hesitate to ask.

    namespace LRUCache
    {
        public class LRUCache
        {
            private int capacity;
            private Dictionary>> cacheMap = new Dictionary>>();
            private LinkedList> lruList = new LinkedList>();
    
            public LRUCache(int capacity)
            {
                this.capacity = capacity;
            }
    
            [MethodImpl(MethodImplOptions.Synchronized)]
            public V get(K key)
            {
                LinkedListNode> node;
                if (cacheMap.TryGetValue(key, out node))
                {
                    V value = node.Value.value;
                    lruList.Remove(node);
                    lruList.AddLast(node);
                    return value;
                }
                return default(V);
            }
    
            [MethodImpl(MethodImplOptions.Synchronized)]
            public void add(K key, V val)
            {
                if (cacheMap.Count >= capacity)
                {
                    RemoveFirst();
                }
    
                LRUCacheItem cacheItem = new LRUCacheItem(key, val);
                LinkedListNode> node = new LinkedListNode>(cacheItem);
                lruList.AddLast(node);
                cacheMap.Add(key, node);
            }
    
            private void RemoveFirst()
            {
                // Remove from LRUPriority
                LinkedListNode> node = lruList.First;
                lruList.RemoveFirst();
    
                // Remove from cache
                cacheMap.Remove(node.Value.key);
            }
        }
    
        class LRUCacheItem
        {
            public LRUCacheItem(K k, V v)
            {
                key = k;
                value = v;
            }
            public K key;
            public V value;
        }
    }
    

提交回复
热议问题