JavascriptMemoization cache function instructions _ javascript skills

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

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.