As an example
Copy Code code as follows:
var flower= function () {
var t=0,i=0;
for (; i<5000000;i++) {
t++;
}
return t;
}
Flower returns the value of T
Suppose this function takes 2-3 seconds.
Through the Memoization function, to find the same value again, directly obtain the cached value, immediately return;
memoization function
Copy Code code as follows:
var memoize = function (FN, cache, Refetch, obj) {
Cache = Cache | | {};//is used to cache results
return function () {
var k = arguments[1]? Array.prototype.join.call (arguments, ' __ '): arguments[0];//multiple parameters are separated by ' __ '
if (!) ( K in cache) | | (Refetch && cache[k] = = Refetch)) {///if it is not in the cached list and is equal to the given Refetch value, re-operation
Cache[k] = fn.apply (obj | | fn, arguments); The obj parameter can be used to change the this pointer
}
Return cache[k];//returns results
}
}
Demo:
<! DOCTYPE html> <ptml> <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; for (; i<12110000;i++) {t++; } return t; var test2 = memoize (test) alert (Test2 ()); Alert (Test2 ()); })(); </script></BODY> </HTML>
[ctrl+a All selected note: If you need to introduce external JS need to refresh to perform]