. Net-Cache Mechanism (1): Simulate cache Using Dictionary
In computer hardware design, there is an idea of repeated use-cache. Similarly, in software design, this idea can also be used to solve the performance problems caused by time-consuming Data Reading (of course, we need to find a balance between time and space ).
First, let's look at how the ideal cache is described:
Static Func
Cache
(Func
Func) {var mem = new Dictionary
(); Return x => {if (! Mem. ContainsKey (x) {Console. WriteLine ("not cached, cache in progress! "); Mem [x] = func (x);} return mem [x] ;};}
Generally, it is to input a T and then spit out an R.
Run:
# Region uses dictionaries to Cache functions. var cacheFunc = Cache
(DoSomeTing); Console. writeLine (cacheFunc (10); Console. writeLine (cacheFunc (5); Console. writeLine (cacheFunc (10); Console. readKey (); # endregion
Among them, DoSomeThing can be an operation to read the database, complex computing operations, etc. Here, only a simple meaning is written:
static int DoSomeTing(int a) { return a * a; }
The next function is interesting. Imagine if the value of dictionary is a dictionary type data?
Static Func
DoSomeTing () {var dic = new Dictionary
> (); Return (a, B) => {if (! Dic. ContainsKey (a) {Console. WriteLine ("a is {0} and B is {1} Not cached! ", A, B); dic [a] = new Dictionary
(); Dic [a] [B] = a + B;} else {if (! Dic [a]. containsKey (B) {Console. writeLine ("a is {0} already cached, B is {1} Not cached, in cache", a, B ); dic [a] [B] = a + B;} return dic [a] [B];}
Run:
//var sfunc = DoSomeTing(); var sfunc=Cache
>(x=>Cache
(y => x+y)); Console.WriteLine(sfunc(10)(5)); Console.WriteLine(sfunc(5)(10)); Console.WriteLine(sfunc(10)(5)); Console.ReadKey();
Does cache the dictionary mean a bit of cache dependency?