I believe we all wrote a recursive function, the following is a typical recursive function:
function fibonacci(n) { return n < 2 ? n : fibonacci(n - 2) + fibonacci(n - 1); }
But like recursive function there is a very obvious problem, each invocation of the need to recalculate the results, so too deep recursion would occupy too much memory causes a stack overflow.
In view of this situation, we can use caching policy to cache the value in the middle.
var fibonacci = function(){ let cache = {}; return function(n){ if(!cache[n]){ cache[n] = n < 2 ? n : fibonacci(n-2) + fibonacci(n-1); } return cache[n]; } }();
The above method using a closure, declare a local variable to hold the calculated value of the cache buffer, you can try more in the console when a recursive hierarchy performance has been greatly improved.
Here to explain, why use the cache = {}, rather than cache = [], because the cache = {} performance will be higher (in fact, will use some more scenes, key not limited to digital), if set the cache = [], set cache [100], when, in fact, just want to set the target value of 100 as a key, the result will be an array of 0-99 will be initialized to empty, and set the object, then it will only set the key to this one 100.
Here again a layer of packaging, as a function of a buffer for general recursive function.
let memoize = function(func) { let cache = {}; return function(key) { if (!cache[key]){ cache[key] = func.apply(this, arguments); } return cache[key]; } } let fibonacci = memoize(function(n) { return n < 2 ? n : fibonacci(n - 2) + fibonacci(n - 1); });
Summary: In fact, very simple principle, is to declare a variable to cache intermediate values, in fact, see a lot of source code framework, have used this method to improve performance, we usually can also be used up during maintenance own component libraries or write business code.