Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Common/MostRecentlyUsedCache.cs @ 11842

Last change on this file since 11842 was 11799, checked in by gkronber, 8 years ago

#2283: performance tuning and reactivated random-roll-out policy in sequential search

File size: 1.4 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Linq;
5using System.Text;
6using System.Threading.Tasks;
7
8namespace HeuristicLab.Common {
9  public class MostRecentlyUsedCache<TKey, TValue> {
10
11    private LinkedList<KeyValuePair<TKey, TValue>> lruList;
12    private Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> dictionary;
13    private int maxCapacity;
14
15    public MostRecentlyUsedCache(int maxCapacity) {
16      this.maxCapacity = maxCapacity;
17      lruList = new LinkedList<KeyValuePair<TKey, TValue>>();
18      dictionary = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(maxCapacity);
19    }
20
21    // drops the least-recently used element if necessary
22    public void Add(TKey key, TValue value) {
23      if (lruList.Count >= maxCapacity) {
24        dictionary.Remove(lruList.Last.Value.Key);
25        lruList.RemoveLast();
26      }
27      lruList.AddFirst(new KeyValuePair<TKey, TValue>(key, value));
28      dictionary.Add(key, lruList.First);
29    }
30
31    public bool TryGetValue(TKey key, out TValue value) {
32      // find matching element
33      LinkedListNode<KeyValuePair<TKey, TValue>> node = null;
34      if (!dictionary.TryGetValue(key, out node)) {
35        value = default(TValue);
36        return false;
37      } else {
38        lruList.Remove(node);
39        lruList.AddFirst(node);
40        value = node.Value.Value;
41        return true;
42      }
43    }
44  }
45}
Note: See TracBrowser for help on using the repository browser.