Javascript memoization Caching function usage Instructions _javascript tips

Source: Internet
Author: User
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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.