Home >Web Front-end >JS Tutorial >Javascript Memoization caching function instructions_javascript skills

Javascript Memoization caching function instructions_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:26:061363browse
For example
Copy code The code is as follows:

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
Copy code 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 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:

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn