JavaScript parses memory allocation and management mechanisms in detail

  • 2020-03-27 00:08:13
  • OfStack

You may have heard that JAVA,.net, and PHP have memory management mechanisms for garbage collection, but you rarely hear that JavaScript has its own memory management mechanism. This article mainly describes the JavaScript garbage collection principle and the specific process.

Introduction to the
In the underlying languages, such as C, there are dedicated memory management mechanisms, such as malloc() and free(). Javascript has a garbage collection mechanism, which means that the JS interpreter automatically allocates and reclaims memory. So people think, I'm using a high-level language, so I don't have to worry about memory management, but that's not true.

The life cycle of memory
Although the languages are different, the memory life cycle is similar in each language:

Allocate memory when needed
2. Read and write to memory
Release the memory allocated above when it is no longer needed
For steps 1,2, almost all languages are explicitly or intuitively manipulable, and there's not much to say. In a high-level language like Javascript, the third step is less intuitive.

Memory space is allocated in Javascript
Variable initialization
When a variable is initialized, Javascript will automatically allocate the corresponding memory space.

Var n = 123; / /   Allocate space for Numbers
Var s = "azerty" scored with; / / string

Var o = {
A: 1,
B: null
}; // allocates memory space for the object and the properties it contains

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

The function f (a) {
Return a + 2;
} // allocates space to the function

/ /   Functions also sometimes allocate object space
SomeElement. AddEventListener (' click ', function () {
SomeElement. Style. BackgroundColor = 'blue'; // personal note, unverified, space will be allocated for someElement, as the comment says, for the object
}, false);

Allocate space when the function is called
Some function calls result in the above - mentioned allocation of space for the object

Var d = new Date();
Var e = document. The createElement method (' div '); / / allocates an DOM element and the below

Var s = "azerty" scored with;
Var s2 = s.ubstr (0, 3); // s2 is a new string
// since strings are immutable in Javascript, Javascript may not allocate new space for strings in s2, but only store [0, 3] intervals (for indexing)

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

Operation variable value
Nothing to say, read, write, function call.

When memory is no longer being used, free it
Many problems with memory management mechanisms arise here. The most troublesome problem is to confirm that "this memory space is no longer needed". This often requires the programmer to tell you, in this program, this memory is no longer needed, you reclaim it.

Embedded in the high-level language interpreter is a tool called garbage collector, which tracks memory allocation and usage so that they can be automatically collected when they are not needed. The problem, however, is that there is uncertainty about whether a block of memory is still useful, which means that it is impossible to calculate accurately with an algorithm.

The garbage collection
For the reasons described above, the garbage collection mechanism takes a limited approach to dealing with the uncertainty above. The following is the idea of centralized garbage collection algorithm and the corresponding limitations:

This method USES the idea of a quote. When a can access a, it is said that a refers to a (directly or indirectly). For example, a Javascript object will reference its stereotype (indirect reference) and its various properties (direct reference).

In this case, the object is extended more broadly, including the scope chain (or global lexical scope) of the function on top of the native object.

Reference counting
This method is the most naive garbage collection algorithm. It define the standard of "recycling" for "no others refer to the object" (the original: This algorithm reduces the definition of "the an object is not men anymore" to "the an object has no other object referencing to it"). That is, objects are garbage collected only when they are not referenced.

For example
Var o = {// is called the outer object
A: {// is called an inner object
B: 2
}; / /   Two inner objects are created to be referenced as properties of the outer objects
// while the outer object is referenced by the variable o
// obviously, no one will be garbage collected

Var o2 = o; // o2 also refers to the outer objects mentioned above. Ok, now the outer object's reference count is' 2' (referenced by o and o2)
O = 1; / /   Now o no longer refers to the outer object, only o2 is referring to it, the reference count is' 1'.

Var oa = o2. A; // oa references inner objects
/ /   The inner object is now referenced by both the properties of the outer object and by oa, with reference count of '2'

O2 = "yukio okamoto,"; / /   Okay, now o2 doesn't refer to the outer object either, the outer object reference count is zero.
// means that the outer object can be "garbage collected"
// however, the inner object is still referenced by oa, so it is still not recycled (personal note: there is a hint of closure here)

Oa = null; / /   Now oa does not refer to inner objects
// inner objects are also garbage collected

Limitation: circular references

See the following code:

The function f () {
Var o = {};
Var o2 = {};
O.a = o2; // o references o2
O2. A = o; // o2 references o

Return "azerty" scored with;

// o o2 two objects constitute a circular reference
// when the functions are finished, they are locked in the scope of f and there is no one outside to use them
// therefore, they are of no value and need to be garbage collected to free memory
// however, none of them have a reference count of "0"
// so they are not recycled under this reference counting mechanism

Practical example
This is the reference counting mechanism used in IE6 and 7 browsers. Therefore, the following code can safely leak memory in IE6,7

Var div = document. The createElement method (" div ");
Div. The onclick = function () {
  DoSomething ();
}; The onclick property of // div refers to function
// however, the function in turn references the div, because div is in the scope of the handler.
// causes the circular reference above, resulting in a memory leak. Tag clearing algorithm

The algorithm defines "recyclable" as "unreachable," or inaccessible.

This algorithm will define a "root" and periodically start from the "root" to find all the objects under the "root" to see if it can find a path from the "root" to refer to the object. From different "roots", the garbage collector can distinguish whether all objects are "unreachable" or not, and when an object is "unreachable", it is collected.

This algorithm is better than the reference counting algorithm. Because "an object has a reference count of 0" implies "this object is unreachable", the reverse statement is false. In other words, this algorithm expands the scope of garbage collection.

Circular references are no longer an obsession
In the circular reference example above, when the function returns, o and o2 are no longer referenced by anyone, i.e., "unreachable," and are automatically garbage collected.

Limitation: objects need to be explicitly "unreachable"
Limited though it is, this rarely happens in practice, so little attention has been paid to it.

Related articles: