For example
var flower= function(){
var t=0,i=0;
for(;i<5000000;i ){
t ;
}
return t;
}
flower returns the value of t
Assume this function takes 2-3 seconds.
Through the Memoization function, when looking for the same value again, the pre-cached value is directly obtained and returned immediately;
Memoization function
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 Separated by '__'
if (!(k in cache) || (refetch && cache[k] == refetch)) { //If it is not in the cache list and is equal to the given refetch value, Re-operate
cache[k] = fn.apply(obj || fn, arguments); //The obj parameter can be used to change this pointer
}
return cache[k];//Return the result
}
}
Demo:
]<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>