JavaScript detailed analysis of memory allocation and management mechanism _ basics

Source: Internet
Author: User

You may have heard of memory management mechanisms for garbage collection in Java,. NET, and PHP languages, but there is little to hear about JavaScript as well as its own memory management mechanism, and JavaScript has similar garbage collection capabilities. This article mainly tells the JavaScript garbage collection principle and the concrete process.

Brief introduction
In the underlying language, such as C, there are special memory management mechanisms, such as malloc () and free (). JavaScript is a garbage collection (garbage collection) mechanism, which means that the JS interpreter automatically allocates and reclaims memory. So some people feel that I use a high-level language, there is no need to care about memory management, in fact, this is wrong.

Life cycle of memory
Although languages are different, the lifecycle of memory in each language is similar:

1. Allocate memory when needed
2. Read and write to memory
3. When the memory allocated above is no longer needed, release them
For 1, 22 steps, almost all language operation is clear or intuitive, there is nothing to say. In a high-level language like JavaScript, the third step is less intuitive.

Allocating memory space in JavaScript
Variable initialization
When the variable is initialized, JavaScript automatically allocates the corresponding memory space (note: Here MDN on the value initialization, in the end is the declaration, or in the assignment time allocated space, but also to learn)

var n = 123; Allocate space for a number
var s = "Azerty"; String

var o = {
A:1,
B:null
}; Allocate memory space for an object and its contained properties

var a = [1, NULL, "Abra"]; (A similar object) allocates space to the array and the elements inside it

function f (a) {
return a + 2;
}//Allocate space for function

Functions also sometimes allocate object space
Someelement.addeventlistener (' click ', function () {
SomeElement.style.backgroundColor = ' Blue '; Personal supplement, not verified, here will allocate space for the someelement, as noted in the note, allocate space for the object
}, False);

Allocate space when function calls
Some function calls, which generate the kind of space allocated to the object.

var d = new Date ();
var e = document.createelement (' div '); Allocates an DOM element and the following

var s = "Azerty";
var s2 = s.substr (0, 3); S2 is a new string
Because the strings in JavaScript are immutable, JavaScript may not allocate new space for strings in S2, but only save [0, 3] intervals (for indexing)

var a = ["Ouais Ouais", "Nan nan"];
var a2 = ["Generation", "Nan nan"];
var a3 = A.concat (A2); New space to store the array A3

Action Variable Value
Nothing to say, read, write, function call.

Release the memory when it is no longer in use
Many of the memory management problems are present here. The most troublesome issue is to confirm that "this memory space is no longer needed." This often requires the programmer to tell, in this program, this piece of memory is not needed, you recycle it.

In the advanced language interpreter, a tool called garbage collection (garbage collector) is embedded to track memory allocations and usage so that they are automatically recycled when they are not needed. However, there is a problem, a piece of memory space is not useful, is uncertain, that is, this can not be accurately calculated by the algorithm.

Garbage collection
As explained above, the garbage collection mechanism has adopted a limited solution to deal with the above uncertainties. The following is an introduction to the idea of a centralized garbage collection algorithm and the corresponding limitations:

Reference
This approach, using a reference to the idea. When a is able to access a, it is said that a refers to a (whether direct or indirect). For example, a JavaScript object would refer to his prototype (indirect reference) and its various attributes (direct reference).

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

Reference count
This method is a garbage collection algorithm that takes the most clothes (naive). It defines the criterion of "recyclable" as "no one else references this object" (Original: This algorithm reduces the definition of ' an object ' is not needed anymore ' to ' an object ha s no other object referencing to it). That is, the object is recycled as garbage only when it is not referenced.

As an example
var o = {//called outer object
A: {//called an inner object
B:2
}
}; Two object inner layer objects are referenced as properties of the outer object
And the outer object is referenced by the variable O
Apparently, no one is going to be garbage collected.

var O2 = O; O2 also quotes the outer object as described above. Okay, now the reference count for the outer object is ' 2 ' (referenced by O and O2)
o = 1; Now o no longer references the outer object, only O2 is referenced, the reference count is ' 1 '

var oa = o2.a; OA refers to the inner layer object
Now the inner object is both a property reference and an OA reference to the outer object, and the reference count is ' 2 '

O2 = "Yo"; OK, now O2 does not reference the outer object, the Outer object reference count is "0"
means that the outer object can be "garbage collected"
However, the inner object is also referenced by OA, so it is still not recycled (Personal note: Here is a bit of closure meaning)

OA = null; Now OA does not refer to the inner object.
Inner objects are also garbage collected

Limitations: Circular References

Look at the following code:

function f () {
var o = {};
var O2 = {};
O.A = O2; o Reference O2
o2.a = O; O2 reference O

return "Azerty";
}

f ();
o O2 two objects form a circular reference
When the function is finished, they are locked in the scope of F, and no one outside can use them
So it stands to reason that they are no longer valuable, need to be garbage collected, free memory
However, their reference count is not "0"
So under the mechanism of this reference counting, they are not recycled

Practical examples
In the ie6,7 version of the browser, the reference counting mechanism is used. Therefore, the following code can stabilize the memory leak in the ie6,7

var div = document.createelement ("div");
Div.onclick = function () {
DoSomething ();
}; Div's OnClick property, which references the function
This function, in turn, refers to this div, because the div is in the handler scope.
This circular reference results in a memory leak. Tag Cleanup algorithm

This algorithm defines "can recycle" as "Object unreachable", that is, inaccessible.

This algorithm defines a "root" and periodically starts with "root" to find all the objects under "root" to see if you can find a path from "root" to refer to the object. From the different "root", the garbage collector can distinguish all objects are not "unreachable", when the object "unreachable" time, it was recycled.

This algorithm is better than the reference counting algorithm. Because "the reference count of an object is 0" can be introduced "This object cannot be reached", the inverse proposition is false. In other words, this algorithm expands the scope of garbage collection.

Circular references are no longer bothered
In the example of the circular reference above, when the function returns, O and O2 are no longer referenced by anyone, that is, "unreachable", which is logically recycled.

Limitations: The object needs a clear "unreachable"
Although it is limited, this situation rarely occurs in practice, so few people are concerned.

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.