Detailed analysis of javascript memory management_basic knowledge
Introduction
Low-level languages, such as C, have low-level memory management commands, such as malloc() and free(), which require developers to manually release memory. However, the situation in high-level languages such as JavaScript is different. Objects (objects, strings, etc.) allocate memory when they are created. When they are no longer in use, the memory will be automatically recycled. This automatic recycling process is called garbage collection. Because of the existence of garbage collection, developers of high-level languages such as JavaScript have a wrong understanding, thinking that they don't need to care about memory management.
Memory life cycle
No matter what programming language, the life cycle of memory is basically the same.
1. Allocate the memory you need
2. Use it for reading and writing operations
3. Release resources when memory is no longer needed
Steps 1 and 2 are the same for all languages and can be clearly noticed. As for step 3, low-level languages require developers to perform this explicitly. For high-level languages like JavaScript, this part of the operation is done by the parser, so you won't notice it.
Assignment operation in javascript
Initialization of value
When assigning a value to a variable, JavaScript will complete the memory allocation.
var n = 123; // Allocate memory for numbers
var s = "azerty"; // Allocate memory for string
var o = {
a: 1,
b: null
}; // Contain attribute value The object object allocates memory
var a = [1, null, "abra"]; // Allocate memory for the array containing the value
function f(a){
return a 2;
} // Allocate memory for the function (function is a callable object)
// Function expression is also an object, and there is a case of allocating memory
someElement.addEventListener('click' , function(){
someElement.style.backgroundColor = 'blue';
}, false);
Allocation is completed by function call
After some functions are executed, object allocation also occurs.
var d = new Date();
var e = document.createElement('div'); // Allocate a DOM element
Some methods allocate new values or objects.
var s = "azerty";
var s2 = s.substr(0, 3); // s2 is a new string
// Since the string is unchanged, javascript will create a new string for the content in the range [0, 3]
var a = ["ouais ouais", "nan nan"];
var a2 = ["generation", "nan nan"];
var a3 = a.concat(a2); // Combine a and a2 together to generate a new array
Use of values
The use of values is actually to perform read and write operations on the allocated memory. These operations include: reading and writing operations on variables or object properties, or passing parameters to functions.
Release memory when no longer needed
Most memory management problems occur at this stage. The hardest thing to do is how to determine when the allocated memory is no longer needed. This often requires developers to determine when the program no longer needs memory and release the resources it occupies.
A program called the "garbage collector" is embedded in the high-level language parser. His job is to track the allocation and use of memory, determine whether the memory is needed, and perform resource release operations when it is no longer needed. . He can only obtain an approximation, because determining whether a memory is needed is an uncertain problem (cannot be solved by an algorithm).
Garbage Collection
As mentioned above, we cannot accurately and automatically determine that "memory is no longer needed". Therefore, garbage collection has limitations as a solution to this problem. This section explains the concepts necessary to understand the major garbage collection algorithms and their limitations.
Quote
A major concept in garbage collection is references. In memory management, when an object uses another object, whether explicitly or implicitly, we say that it refers to another object. For example, a JavaScript object has an implicit reference to its prototype and explicit references to its property values.
Here, the concept of object goes beyond the traditional concept of object in JavaScript. It also includes function scope and global scope.
Garbage collection using reference counting algorithm
What is introduced below is an optimal algorithm, which introduces the concepts of "the object is no longer needed" and "no other objects refer to the object". When the object's reference pointer becomes 0, it is considered ready for recycling.
Example:
var o = {
a: {
b:2
}
}; // Two objects are created. One object (a) is referenced by another object (the object referenced by o), and uses a as its attribute
// The object is referenced by variable o again
// Obviously, no object can be recycled at this time
var o2 = o; // Variable o2 references the object again
o = 1; // o no longer refers to the object, only o2 still refers to the object
var oa = o2.a; // oa refers to the attribute object a of o2
// This object is referenced by two other objects, namely the attribute a of o2 and the oa variable
o2 = "yo"; // This object is no longer referenced by other objects, but its attribute a is still It is referenced by the oa variable, so it cannot be released yet
oa = null; // Now attribute a is no longer referenced by other objects, and the object can be recycled
Restriction: Loop
This algorithm has its limitations. When an object refers to another object and a circular reference is formed, the garbage collector will not reclaim them even if they are no longer needed.
function f(){
var o = { };
var o2 = {};
o.a = o2; // o refers to o2
o2.a = o; // o2 refers to o
return "azerty";
}
f();
// Two objects are created and form references to each other
// After the function call ends, they will not leave the function scope, although they will not be Used, but will not be released
// This is because the reference counting algorithm determines that as long as the object is referenced, garbage collection cannot be performed on it
Reality In the examples in
ie6 and 7, the reference counting algorithm is used on the DOM object, and there will be a memory leak problem.
var div = document.createElement("div");
div.onclick = function(){
doSomething();
}; // div refers to the event handler through the click attribute
// When the div variable is accessed in the event handler function , will form a circular reference, which will cause both objects to not be recycled, causing memory leaks
Tag - Clear Algorithm
He introduced the concepts of "object no longer needed" and "object unreachable (object unreachable)". This algorithm assumes that there is a series of root objects (the root object in JavaScript is the global object). Every once in a while, the garbage collector will start from the root object, traverse all the objects it references, and then traverse the objects referenced by the reference object. And so on. Using this approach, the garbage collector can obtain all accessible objects and reclaim those that are inaccessible.
This algorithm is better than the previous algorithm. Objects referenced by 0 will be set as inaccessible objects. At the same time, it also avoids the trouble caused by circular references.
As of 2012, most modern browsers use this "mark-and-sweep" garbage collector. The field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) has improved the algorithms related to it in the past few years, but the garbage collection algorithm itself (mark-sweep algorithm) and "how to determine whether an object is no longer need" has not been improved.
Cycle is no longer an issue
In the first example, after the function call ends, these two objects will not be referenced by the global object, nor will they be referenced by the object referenced by the global object. Therefore, they will be marked as inaccessible objects by the JavaScript garbage collector. The same thing happens in the second example, when the div and event handler are marked as inaccessible by the garbage collector, they will be released.
Restriction: Objects need to be explicitly marked as inaccessible
This marking method has limitations, but we have not been exposed to it in programming, so we rarely care about garbage collection related content.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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 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 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 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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment