In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you how JavaScript memory management introduction is, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.
Most of the time, we only develop without knowing anything about memory management, because the JS engine will handle this problem for us. However, sometimes we encounter problems such as memory leaks, which can only be solved by knowing how memory allocation works.
This paper mainly introduces the working principle of memory allocation and garbage collection and how to avoid some common memory leakage problems.
Cache (Memory) lifecycle
In JS, when we create a variable, function, or any object, the JS engine allocates memory for it and frees it when it is no longer needed.
Allocating memory is the process of keeping space in memory, while freeing memory frees up space for other purposes.
Every time we assign a variable or create a function, the storage of that variable goes through the following same stages:
Allocate memory
JS handles this problem for us: it allocates the memory we need to create objects.
Using memory is what we do explicitly in our code: reading and writing to memory is actually reading and writing to variables.
Free memory
This step is also handled by the JS engine, and after the allocated memory is freed, it can be used for new purposes.
"objects" in the context of memory management include not only JS objects, but also functions and function scopes.
Memory heap and heap
Stack We now know that for everything we defined in JS, the engine allocates memory and frees it when it is no longer needed.
The next question that comes to mind is: where will these things be stored?
The JS engine can store data in two places: the memory heap and the stack. Heaps and stacks are two data structures that engines are used for different purposes.
Stack: static memory allocation
The stack is the data structure that JS uses to store static data. Static data is data that the engine knows the size of at compile time. In JS, it includes raw values (strings,number,boolean,undefined and null) and reference types that point to objects and functions.
Because the engine knows that the size will not change, it will allocate a fixed amount of memory for each value.
The process of allocating memory immediately before execution is called static memory allocation. These values and the limits of the entire stack depend on the browser.
A heap is another place where data is stored, where JS stores objects and functions.
Unlike the stack, the JS engine does not allocate a fixed amount of memory to these objects, but allocates space as needed. This way of allocating memory is also known as dynamic memory allocation.
The characteristics of the two stores are compared below:
The stack stores basic types and references
The size is known at compile time
Allocate a fixed number of memory objects and functions
The size is known only at run time.
There are no restrictions.
Case study
Here are a few examples to enhance the image.
Const person = {name: 'John', age: 24,}
JS allocates memory for this object in the heap. The actual values are still original values, which is why they are stored in the stack.
Const hobbies = ['hiking',' reading']
Arrays are also objects, which is why they are stored in the heap.
Let name = 'John'; / / allocate memory for strings const age = 24; / allocate memory for words name =' John Doe'; / / allocate memory for new strings const firstName = name.slice (0line 4); / / allocate memory for new strings
The initial value is immutable, so JS does not change the original value, but creates a new value.
References in JavaScript
All variables first point to the stack. If it is a non-original value, the stack contains references to objects in the heap.
The memory of the heap is not sorted in a specific way, so we need to keep a reference to it in the stack. We can think of references as addresses and objects in the heap as houses to which these addresses belong.
Remember that JS stores objects and functions in the heap. Basic types and references are stored in the stack.
In this photo, we can see how to store different values. Notice how both person and newPerson point to the same object.
Case study
Const person = {name: 'John', age: 24,}
This creates a new object in the heap and a reference to that object in the stack.
Garbage collection
Now we know how JS allocates memory for various objects, but in the memory life cycle, there is one final step: freeing up memory.
Just like memory allocation, the JavaScript engine handles this step for us. More specifically, the garbage collector is responsible for this work.
Once the JS engine recognizes that a variable or function is no longer needed, it frees up its memory.
The main problem with this is that whether some memory is still needed is an uncertain problem, which means that it is impossible for an algorithm to collect all the memory that is no longer needed at the moment it is no longer needed.
Some algorithms can solve this problem very well. I will discuss the most commonly used methods in this section: reference counting and tag removal algorithms.
Reference count
When a variable is declared and a reference type value is assigned to the variable, the number of references to that value is 1. If the same value is assigned to another variable, the number of references should be increased by 1. Conversely, if the variable that contains a reference to this value can take another value, the number of references to that value is subtracted by 1.
When the number of references to this value becomes 0, there is no way to access the value, so the memory space it occupies can be recovered. In this way, the next time the garbage collector runs, it frees the memory occupied by those values with zero references.
Let's look at the following example.
Notice that in the last frame, only hobbies is left in the heap, because the last reference is the object.
Cycle number
The problem with the reference counting algorithm is that it does not consider circular references. This occurs when one or more objects refer to each other but can no longer be accessed through code.
Let son = {
Name: 'John'
}
Let dad = {
Name: 'Johnson'
}
Son.dad = dad
Dad.son = son
Son = null
Dad = null
Because the parent objects refer to each other, the algorithm does not release the allocated memory, and we can no longer access the two objects.
Setting them to null does not cause the reference counting algorithm to recognize that they are no longer used because they all have incoming references.
Mark clear
The tag removal algorithm has a solution to circular dependencies. It detects whether they can be accessed from root objects, rather than simply calculating references to a given object.
The root of the browser is the window object, while the root in NodeJS is global.
The algorithm marks inaccessible objects as garbage and then scans (collects) them.
In this way, circular dependencies are no longer a problem. In the previous example, neither the dad object nor the son object can be accessed from the root. Therefore, they will all be marked as garbage and collected.
Since 2012, the algorithm has been implemented in all modern browsers. Only the performance and implementation are improved, the core idea of the algorithm is still the same.
Compromise
Automatic garbage collection allows us to focus on building applications without wasting time on memory management.
Memory usage
Because algorithms don't know exactly when memory is no longer needed, JS applications may use more memory than they actually need.
Even if the object is marked as garbage, it is up to the garbage collector to decide when and whether the allocated memory will be collected.
If you want your application to be as memory efficient as possible, it's best to use a low-level language. But remember, this requires a trade-off.
Performance
Garbage collection algorithms are usually run periodically to clean up unused objects.
The problem is that we developers don't know when it will be recycled. Collecting a large amount of garbage or collecting garbage frequently can affect performance. However, users or developers usually do not notice this impact.
Memory leak
When storing data in global variables, the most common memory problem may be memory leaks.
In the browser's JS, if var,const or let is omitted, the variable is added to the window object.
Users = getUsers ()
This can be avoided in strict mode.
In addition to accidentally adding a variable to the root directory, in many cases we need to use the global variable this way, but remember to release it manually once you don't need it.
It's easy to release it, just give it null.
Window.users = null
Forgotten timers and callbacks
Forgetting timers and callbacks can increase the memory usage of our application. Especially in single-page applications (SPA), care must be taken when adding event listeners and callbacks dynamically.
Forgotten timer
Const object = {}; const intervalId = setInterval (function () {/ / everything used here cannot be collected until `setInterval` doSomething (object) is cleared;}, 2000)
The above code runs the function every 2 seconds. If we have such code in our project, we probably don't need to run it all the time.
As long as the setInterval is not canceled, the referenced objects will not be garbage collected.
Be sure to clear it when it is no longer needed.
ClearInterval (intervalId)
Suppose we add an onclick listener to the button, after which the button will be removed. Old browsers could not collect listeners, but now this is no longer a problem.
However, it is still a good idea to delete event listeners when we no longer need them.
Const element = document.getElementById ('button'); const onClick = () = > alert (' hi'); element.addEventListener ('click', onClick); element.removeEventListener (' click', onClick); Element [XSS _ Child] .removeChild (element)
The memory leak is similar to the previous memory leak: it occurs when the DOM element is stored in JS.
Const elements = []; const element = document.getElementById ('button'); elements.push (element); function removeAllElements () {elements.forEach ((item) = > {document.body.removeChild (document.getElementById (item.id))});}
When deleting these elements, we also need to make sure that the element is also removed from the array. Otherwise, these DOM elements cannot be collected.
Const elements = []; const element = document.getElementById ('button'); elements.push (element); function removeAllElements () {elements.forEach ((item, index) = > {document.body.removeChild (document.getElementById (item.id)); elements.splice (index, 1);});}
Because each DOM element also retains a reference to its parent node, you can prevent the garbage collector from collecting the element's parent and child elements.
The above is what the introduction to JavaScript memory management is like. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.