Functions can use objects to remember the results of previous operations, so as to avoid unnecessary operations. Such optimization is called memory ). It is very convenient to optimize JavaScript objects and arrays.
Memoization is a method for caching function return values. It is widely used in LISP, Ruby, Perl, Python, and other languages. With the rise of Ajax, client requests to servers become increasingly intensive (Classic, such as AutoComplete). If there is a good caching mechanism, then the client JavascriptProgramIs obvious.
The memoization principle is very simple, that is, to put each execution result of a function into a hash, and in the next execution, find whether the values have been executed in the hash list, if yes, this value is directly returned, and the evaluation part of the function body is not actually executed. Obviously, finding a value, especially in a hash, is much faster than executing a function. This technology has been widely used in modern Javascript development.
For example, we want a recursive function to calculate the Fibonacci series. A Fibonacci number is the sum of the first two. The first two digits are 0 and 1.
VaRFibonacci =Function(N ){ReturnN <2? N: Maid (n-1) + Maid (n-2);};For(VaRI =0; I <=10; I + =1){Document. Writeln ('//'+ I +':'+ Maid (I ));}// 0: 0// 1: 1// 2: 1// 3: 2// 4: 3// 5: 5// 6: 8// 7: 13// 8: 21// 9: 34// 10: 55
This can work, but it does a lot of unnecessary work. The Fibonacci function is called 453 times. We called it 11 times, and it called it 442 times to calculate the value that may have just been computed. If we enable this function to have a memory function, we can significantly reduce its computing workload.
We store our stored results in an array named memo, and the stored results can be hidden in the closure. When our function is called, the function first checks whether the calculation result is known. If the result is known, the stored result is returned immediately.
VaRFibonacci =Function(){VaRMemo = [0,1];VaRFIB =Function(N ){VaRResult = memo [N];If(TypeofResult! ='Number') {Result = fib (n-1) + Fib (n-2); Memo [N] = result ;}ReturnResult ;};ReturnFIB ;}();
This function returns the same result, but it is only called 29 times. We called it 11 times and it called it 18 times to get the previously stored results.