search
HomeWeb Front-endJS TutorialFunction memory of JavaScript learning notes

Function memory of JavaScript learning notes

Jan 25, 2018 am 11:03 AM
javascriptjsmemory

This article mainly introduces the function memory of JavaScript study notes. The editor thinks it is quite good. Now I will share the JavaScript source code with you and give you a reference. If you are interested in JavaScript, please follow the editor to take a look.

This article explains the implementation of function memory and Fibonacci sequence and shares it with everyone. The details are as follows

Definition

Function memory refers to caching the last calculation result. When the next call is made, if the same parameters are encountered, the data in the cache will be returned directly.

For example:

function add(a, b) {
  return a + b;
}

// 假设 memorize 可以实现函数记忆
var memoizedAdd = memorize(add);

memoizedAdd(1, 2) // 3
memoizedAdd(1, 2) // 相同的参数,第二次调用时,从缓存中取出数据,而非重新计算一次

Principle

It is very simple to implement such a memorize function. In principle, you only need to combine the parameters with the corresponding The result data is stored in an object. When called, it is judged whether the data corresponding to the parameter exists. If it exists, the corresponding result data is returned.

First version

Let’s write a version:

// 第一版 (来自《JavaScript权威指南》)
function memoize(f) {
  var cache = {};
  return function(){
    var key = arguments.length + Array.prototype.join.call(arguments, ",");
    if (key in cache) {
      return cache[key]
    }
    else return cache[key] = f.apply(this, arguments)
  }
}

Let’s test it:

var add = function(a, b, c) {
 return a + b + c
}

var memoizedAdd = memorize(add)

console.time('use memorize')
for(var i = 0; i < 100000; i++) {
  memoizedAdd(1, 2, 3)
}
console.timeEnd(&#39;use memorize&#39;)

console.time(&#39;not use memorize&#39;)
for(var i = 0; i < 100000; i++) {
  add(1, 2, 3)
}
console.timeEnd(&#39;not use memorize&#39;)

In In Chrome, using memorize takes about 60ms. If we don't use the functionmemory, it takes about 1.3 ms.

Note

What, we used the seemingly advanced function memory, but it turned out to be more time-consuming, almost 60 times in this example!

So, function memory is not omnipotent. If you look at this simple scenario, it is not suitable for function memory.

It should be noted that function memory is just a programming technique. It essentially sacrifices the space complexity of the algorithm in exchange for better time complexity. The code in client JavaScript Execution time complexity often becomes a bottleneck, so in most scenarios, this approach of sacrificing space for time to improve program execution efficiency is very desirable.

Second Edition

Because the first edition uses the join method, we can easily think that when the parameter is an object, the toString method will be automatically called. Convert it to [Object object], and then concatenate the string as the key value. Let’s write a demo to verify this problem:

var propValue = function(obj){
  return obj.value
}

var memoizedAdd = memorize(propValue)

console.log(memoizedAdd({value: 1})) // 1
console.log(memoizedAdd({value: 2})) // 1

Both return 1, which is obviously a problem, so let’s take a look at how underscore’s memoize function is implemented:

// 第二版 (来自 underscore 的实现)
var memorize = function(func, hasher) {
  var memoize = function(key) {
    var cache = memoize.cache;
    var address = &#39;&#39; + (hasher ? hasher.apply(this, arguments) : key);
    if (!cache[address]) {
      cache[address] = func.apply(this, arguments);
    }
    return cache[address];
  };
  memoize.cache = {};
  return memoize;
};

From It can be seen from this implementation that underscore uses the first parameter of the function as the key by default, so if you use

var add = function(a, b, c) {
 return a + b + c
}

var memoizedAdd = memorize(add)

memoizedAdd(1, 2, 3) // 6
memoizedAdd(1, 2, 4) // 6

directly, there must be a problem. If you want to support multiple parameters, we need to pass in the hasher function, since Define the stored key value. So we consider using JSON.stringify:

var memoizedAdd = memorize(add, function(){
  var args = Array.prototype.slice.call(arguments)
  return JSON.stringify(args)
})

console.log(memoizedAdd(1, 2, 3)) // 6
console.log(memoizedAdd(1, 2, 4)) // 7

If you use JSON.stringify, the problem that the parameter is an object can also be solved, because the string after object serialization is stored.

Applicable scenarios

We take the Fibonacci sequence as an example:

var count = 0;
var fibonacci = function(n){
  count++;
  return n < 2? n : fibonacci(n-1) + fibonacci(n-2);
};
for (var i = 0; i <= 10; i++){
  fibonacci(i)
}

console.log(count) // 453

We will find that the final count is 453, This means that the fibonacci function has been called 453 times! Maybe you are thinking, I just looped to 10, why was it called so many times, so let’s analyze it in detail:

When fib(0) is executed, it is called 1 time

When executing fib(1), it is called once

When executing fib(2), it is equivalent to fib(1) + fib(0) plus fib(2) itself this time, a total of 1 + 1 + 1 = 3 times

When executing fib(3), it is equivalent to fib(2) + fib(1) plus fib(3) itself this time, a total of 3 + 1 + 1 = 5 times

When executing fib(4), it is equivalent to fib(3) + fib(2) plus fib(4) itself this time, a total of 5 + 3 + 1 = 9 times

When When executing fib(5), it is equivalent to fib(4) + fib(3) plus fib(5) itself this time, a total of 9 + 5 + 1 = 15 times

When executing fib(6) , equivalent to fib(5) + fib(4) plus fib(6) itself this time, a total of 15 + 9 + 1 = 25 times

When executing fib(7), it is equivalent to fib(6 ) + fib(5) plus fib(7) itself this time, a total of 25 + 15 + 1 = 41 times

When executing fib(8), it is equivalent to fib(7) + fib(6) Adding fib(8) itself this time, a total of 41 + 25 + 1 = 67 times

When executing fib(9), it is equivalent to fib(8) + fib(7) plus fib(9) This time itself, a total of 67 + 41 + 1 = 109 times

When executing fib(10), it is equivalent to fib(9) + fib(8) plus fib(10) This time itself, a total of 109 + 67 + 1 = 177 times
So the total number of executions is: 177 + 109 + 67 + 41 + 25 + 15 + 9 + 5 + 3 + 1 + 1 = 453 times!

What if we use function memory?

var count = 0;
var fibonacci = function(n) {
  count++;
  return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
};

fibonacci = memorize(fibonacci)

for (var i = 0; i <= 10; i++) {
  fibonacci(i)
}

console.log(count) // 12

We will find that the final total number of times is 12 times. Because of the use of function memory, the number of calls is reduced from 453 times to 12 times!

While you are excited, don’t forget to think: Why is it 12 times?

The results from 0 to 10 are stored once each. It should be 11 times? Hey, where did that extra time come from?

So we need to carefully look at our writing method. In our writing method, we actually overwrite the original fibonacci function with the generated fibonacci function. When we execute fibonacci(0), the function is executed once, and the cache is { 0: 0}, but when we execute fibonacci(2), we execute fibonacci(1) + fibonacci(0), because the value of fibonacci(0) is 0, !cache[address] The result If it is true, the fibonacci function will be executed again. It turns out that the extra time is here!

Perhaps you may feel that fibonacci is not used in daily development, and this example seems to have little practical value. In fact, this example is used to illustrate a usage scenario, that is, if a large number of repetitions are required For calculations, or where a large number of calculations depend on previous results, you can consider using function memory. And when you encounter this kind of scene, you will know it.

Related recommendations:

JavaScript function binding usage analysis

Detailed explanation of throttling and anti-shake debounce of JavaScript function

Explain how to use JavaScript function binding

The above is the detailed content of Function memory of JavaScript learning notes. For more information, please follow other related articles on the PHP Chinese website!

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.