Detailed analysis of memory allocation and management mechanisms by JavaScript

Source: Internet
Author: User

You may have heard of JAVA ,. NET, PHP and other languages have garbage collection memory management mechanisms, but few will hear that JavaScript also has its own memory management mechanism. JavaScript also has similar garbage collection functions. This article describes the principles and specific processes of JavaScript garbage collection.

Introduction
In the underlying language, such as C, there is a dedicated memory management mechanism, such as malloc () and free (). Javascript has a garbage collection mechanism, that is, the JS interpreter automatically allocates and recycles memory. In this way, some people think that I am using a high-level language and don't have to worry about memory management. In fact, this is not correct.

Memory Lifecycle
Although the languages are different, the memory lifecycle in each language is similar:

1. allocate memory as needed
2. Perform read/write operations on the memory
3. Release the allocated memory when it is no longer needed.
For steps 1 and 2, almost all language operations are clear or intuitive, and there is nothing to say. In advanced languages like Javascript, the third step is not so intuitive.

Memory Allocation in Javascript
Variable Initialization
When the variable is initialized, Javascript will automatically allocate the corresponding memory space (Note: here, the MDN uses Value initialization to determine whether to declare or allocate space when assigning values, learn more)

Var n = 123; // allocate space for numbers
Var s = "azerty"; // string

Var o = {
A: 1,
B: null
}; // Allocate memory space for the object and its attributes

Var a = [1, null, "abra"]; // (similar to an object) Allocate space to the array and its elements

Function f (){
Return a + 2;
} // Allocate space for the function

// Functions sometimes allocate object space
SomeElement. addEventListener ('click', function (){
SomeElement. style. backgroundColor = 'blue'; // personal supplement, unverified. Space is allocated for someElement, as stated in the comment.
}, False );

Allocate space when calling a function
Some function calls will generate the one mentioned above to allocate space for objects.

Var d = new Date ();
Var e = document. createElement ('div '); // allocates an DOM element has the following

Var s = "azerty ";
Var s2 = s. substr (0, 3); // s2 is a new string
// Because the string in Javascript is unchangeable, Javascript may not allocate new space for the string in s2, but only store the range of [0, 3] (used for indexing)

Var a = ["ouais", "nan"];
Var a2 = ["generation", "nan"];
Var a3 = a. concat (a2); // new space to store array a3

Operation variable value
There is nothing to say: read, write, and function call.

Release the memory when it is no longer in use.
Many problems with the memory management mechanism occur here. The most troublesome problem is to confirm that "this memory space is no longer needed ". This often requires the programmer to inform that the memory in this program is no longer needed. Please recycle it.

The high-level language interpreter embeds a tool called "garbage collector" to track memory allocation and usage, so that they are automatically recycled when they are not needed. However, there is a problem: whether a piece of memory space is still useful is uncertain. That is to say, this cannot be accurately calculated using algorithms.

Garbage Collection
As mentioned above, the garbage collection mechanism has adopted a limited solution to deal with the above uncertainties. The following describes the ideas and limitations of the centralized garbage collection algorithm:

Reference
This method uses a reference idea. When a can access A, it means that A references a (either directly or indirectly ). For example, a Javascript Object references its prototype (indirect reference) and its attributes (direct reference ).

In this case, the object is extended in a broader sense. On the basis of the native object, it also contains the function scope chain (or the global lexical scope ).

Reference count
This method is the garbage collection algorithm that best uses clothes (naive. It defines the "recoverable" standard as "no one else references this object" (original article: this algorithm has CES the definition of "an object is not needed anymore" to "an object has no other object referencing to it "). That is to say, objects are recycled as garbage only when they are not referenced.

For example
Var o = {// It is called an outer object.
A: {// It is called an inner object.
B: 2
}
}; // Two inner objects of an object are created as attributes of the outer object and referenced
// The outer object is referenced by variable o
// Apparently, no one will be reclaimed

Var o2 = o; // o2 also references the outer object mentioned above. Now the reference count of the outer object is '2' (referenced by o and o2)
O = 1; // now o no longer references the outer object. Only o2 is referenced, and the reference count is '1'

Var oa = o2.a; // oa references the inner object
// Now the inner layer object is referenced and referenced by oa as the attribute of the outer layer object at the same time. The reference count is '2'

O2 = "yo"; // Well, now o2 does not reference the outer object, and the reference count of the outer object is "0"
// It means that the outer object can be recycled by garbage collection.
// However, the inner object is still referenced by oa, so it is still not recycled (Note: Here is a closure)

Oa = null; // now oa does not reference the inner object
// The inner layer object is also reclaimed.

Limitation: circular reference

See the following code:

Function f (){
Var o = {};
Var o2 = {};
O. a = o2; // o references o2
O2.a = o; // reference o by o2

Return "azerty ";
}

F ();
// O o2 two objects constitute a circular reference
// When the function execution is complete, they are locked in the scope of f, and no one else can use them.
// It is reasonable to say that they have no value and need to be reclaimed and the memory is released.
// However, their reference count is not "0"
// So under this reference counting mechanism, they are not recycled

Actual Example
In IE6 and 7 browsers, the reference counting mechanism is used. Therefore, the following code may cause memory leakage in IE6 and 7.

Var div = document. createElement ("div ");
Div. onclick = function (){
DoSomething ();
}; // The onclick attribute of the div, which references the function
// However, this function references this div in turn, because the div is in the handler's scope.
// Cause the above loop reference and cause memory leakage. Mark clearing Algorithm

This algorithm defines "recoverable" as "objects inaccessible", that is, access fails.

This algorithm defines a "root" and regularly starts from the "root" to find all objects under the "root, check whether a path from "root" can be used to reference this object. Based on different "Roots", the garbage collection program can identify whether all objects are "inaccessible". When the objects are "inaccessible", they are recycled.

This algorithm is better than the reference counting algorithm. Because "the reference count of an object is 0", "This object is not reachable" can be introduced, and the inverse proposition is false. That is to say, this algorithm expands the scope of garbage collection.

Circular reference is no longer a problem
In the example of circular references above, when the function returns, both o and o2 are no longer referenced by anyone, that is, "unattainable", and are recycled by garbage.

Limitation: the object must be clearly "reachable"
Although it is a limitation, this situation rarely happens in practice, so few people are concerned about this.

Related Article

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.