Beispiel #1
0
        public void Add(int key, string value)
        {
            if (values.ContainsKey(key))
            {
                values[key].UpdateValue(value);
                PromoteEntry(values[key]);
                return;
            }

            if (entriesCount == capacity)
            {
                var evictedEntry = frequencies[minFrequency].RemoveTail();
                values.Remove(evictedEntry.Key);

                if (frequencies[minFrequency].IsEmpty)
                {
                    frequencies.Remove(minFrequency);
                }

                entriesCount--;
            }

            if (!frequencies.ContainsKey(DefaultFrequency))
            {
                frequencies[DefaultFrequency] = new CacheDoubleLinkedList();
            }

            var newEntry = new CacheEntry(key, value);

            frequencies[DefaultFrequency].InsertToHead(newEntry);
            values[key] = newEntry;
            nodeFrequencies[newEntry] = DefaultFrequency;
            minFrequency = DefaultFrequency;
            entriesCount++;
        }
Beispiel #2
0
 public Lru(int capacity)
 {
     values        = new Dictionary <int, CacheEntry>();
     this.capacity = capacity;
     entriesCount  = 0;
     list          = new CacheDoubleLinkedList();
 }
Beispiel #3
0
        private void PromoteEntry(CacheEntry cacheEntry)
        {
            var currentFrequency = nodeFrequencies[cacheEntry];

            frequencies[currentFrequency].Remove(cacheEntry);

            if (frequencies[currentFrequency].IsEmpty)
            {
                frequencies.Remove(currentFrequency);
            }

            var newFrequency = ++currentFrequency;

            if (!frequencies.ContainsKey(newFrequency))
            {
                frequencies[newFrequency] = new CacheDoubleLinkedList();
            }

            frequencies[newFrequency].InsertToHead(cacheEntry);
            nodeFrequencies[cacheEntry] = newFrequency;
        }