static void CustomBasedCache() { MyObject obj1 = new MyObject(); obj1.var1 = 1; obj1.var2 = 1; MyObject obj3 = new MyObject(); obj3.var1 = 2; obj3.var2 = 1; MyObject obj2 = new MyObject(); obj2.var1 = 5; obj2.var2 = 5; LFUCache<MyKey, MyObject> customCache = new LFUCache<MyKey, MyObject>(); MyKey key = customCache.Add(obj1); MyKey key2 = customCache.Add(obj2); MyKey key3 = customCache.Add(obj3); //........ //obj1.var1 + obj1.var2 //OUTPUT: 2 Console.WriteLine("" + (customCache[key].var1 + customCache[key].var2)); //The frequency count will go up 2, because we access it twice MyObject obj = customCache[key3]; //obj3.var1 + obj3.var2 //OUTPUT: 3 Console.WriteLine("" + (obj.var1 + obj.var2)); //The frequency count will go up 1, because we only access it once obj = customCache.LeastFrequentlyUsedObject; //The least frequently used object will be obj2 because we haven't requested it yet. //obj2.var1 + obj2.var2 //OUTPUT: 10 Console.WriteLine("" + (obj.var1 + obj.var2)); //This will be obj2.var1 + obj2.var2 }
private static void TestShrinkFactorOnce(int capacity, float factor) { var cache1 = new LFUCache <int, int>(capacity, factor); foreach (var i in Enumerable.Range(0, capacity)) { cache1.Add(i, 0); } Assert.AreEqual(cache1.Count, capacity); cache1.Add(capacity, 0); Assert.AreEqual(cache1.Count, (int)(capacity * factor) + 1); }
public static void TestGetValue() { var cache = new LFUCache <string, int>(4, 0.5f); cache.Add("a", 1); cache.Add("b", 2); cache.Add("c", 3); cache.Add("d", 4); Assert.AreEqual(cache["a"], 1, "should get 1"); Assert.AreEqual(cache["b"], 2, "should get 2"); Assert.AreEqual(cache["c"], 3, "should get 3"); Assert.AreEqual(cache["d"], 4, "should get 4"); }
public static void TestReplace() { var cache = new LFUCache <string, int>(4, 0.5f); cache.Add("a", 1); cache.Add("b", 2); cache.Add("c", 3); int x = default; x = cache["a"]; x = cache["a"]; x = cache["b"]; cache.Add("d", 4); cache.Add("e", 5); Assert.AreEqual(cache["a"], 1, "should get 1"); Assert.AreEqual(cache["b"], 2, "should get 0"); Assert.IsFalse(cache.ContainsKey("c")); Assert.IsFalse(cache.ContainsKey("d")); Assert.AreEqual(cache["e"], 5, "should get 5"); }