understand the importance of caching in web development by calculating the Fibonacci sequence1. First Test that the Fibonacci sequence is not computed using the data cache.
var count = 0; function fib(n) { count++; if(n === 0 || n === 1) { return 1; } return fib(n - 1) + fib(n - 2); } fib(40); console.log(count);//count是函数fib运算次数,当fib(40)时候运行次数高达:331160281次,感兴趣的可以检测一下。
2. Let's take a look at using the data cache to calculate the Fibonacci sequence.
How is the cache used? The general cache structure is: A key-value pair (object or array)//var obj = {}; var arr = []; How to use Caching://1 Go to the cache first to find out if there is no key corresponding to the data//2 If there is, just bring it to use//3 if not, calculate or query to, then, to put in the cache! After 4, it's time to go through the cache to get data//simplified steps: First out of the cache query there is no, if not the calculation, and put the results in the cache//problem: Where to put the cache?? If it is a global variable, at this point, anyone can modify the contents of the global variable//That is caused by: data inaccurate//var obj = {}; 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 .... var count = 0; var fib = (function () {//Use closures, put the cache in the closure,//At this time, the cache is protected//var cache = {}; var cache = []; This function is used to calculate: Fibonacci sequence return function (n) {count++; 1 go to the cache first to find out if there is no value for the key object if (Cache[n]!== undefined) {//2 if so, return the current value directly Cach E[n]; }//3 if not, calculate and then add to the cache if (n = = = 0 | | n = = = 1) {//return 1; Cache[n] = 1; return cache[n]; } var temp = Arguments.callee (n-1) + Arguments.callee (n-2); Put in the cache to cache[n] = temp; return cache[n]; }; })(); FIB (40); Console.log (count);//The Count is: 79 times.
By comparing the above two times, the importance of the data cache is instantly felt, from 331,160,281 times down to 79 times. The thread of interest can test the FIB (50), run the number of times, do not use the data cache I tested, my browser crashed, and the data cache ran only 99 times.
The importance of data caching in Web sites