Memoization is a way to cache function return values. For details about how to learn js object-oriented users, refer.
For example
The Code is as follows:
Var flower = function (){
Var t = 0, I = 0;
For (; I <5000000; I ++ ){
T ++;
}
Return t;
}
Flower returns t value
Suppose this function takes 2-3 seconds.
Through the Memoization function, when the same value is searched again, the cached value is obtained directly and immediately returned;
Memoization Function
The Code is as follows:
Var Memoize = function (fn, cache, refetch, obj ){
Cache = cache | {}; // used to cache results
Return function (){
Var k = arguments [1]? Array. prototype. join. call (arguments, '_'): arguments [0]; // multiple parameters are separated '_'.
If (! (K in cache) | (refetch & cache [k] = refetch) {// if it is not in the cache list and is equal to the given refetch value, perform the operation again
Cache [k] = fn. apply (obj | fn, arguments); // The obj parameter can be used to change the this pointer.
}
Return cache [k]; // return results
}
}
Demo:
<! DOCTYPE html> <HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> script (function () {var Memoize = function (fn, cache, refetch, obj) {cache = cache |{}; return function () {var k = arguments [1]? Array. prototype. join. call (arguments, '_'): arguments [0]; if (! (K in cache )&&! (Refetch & cache [k] = refetch) {cache [k] = fn. apply (obj | fn, arguments);} return cache [k] ;}} var test = function () {var t = 0, I = 0; (; I <12110000; I ++) {t ++;} return t;} var test2 = Memoize (test) alert (test2 ()); alert (test2 () ;}) (); script </BODY> </HTML>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]