Knowledge of JavaScript errors don't care about memory management _jquery

Source: Internet
Author: User
Tags garbage collection object object

introduce
Lower-level languages, such as C, have low-level memory management commands, such as malloc () and free (), which require developers to manually release memory. However, a high-level language like JavaScript is different, objects (objects, strings, etc.) are created with memory allocated, and when they are not in use the memory is automatically recycled, the process of automatic recycling is called garbage collection. Because of the existence of garbage collection, JavaScript and other high-level language developers have created a false understanding that can not care about memory management.

Memory life cycle
Regardless of the programming language, the lifecycle of memory is basically consistent.
Allocate the memory you need
Use him for read and write operations
Free up resources when memory is not needed
Steps 1 and 2 are the same for all languages and are clearly perceived. As for step 3, low-level languages require developer explicit execution. For a high-level language like JavaScript, this part of the operation is done to the parser, so you won't notice.

assignment operations in JavaScript
Initialization of values
When assigning a value to a variable, JavaScript completes the allocation of memory.

Copy Code code as follows:

var n = 123; allocating memory for a number
var s = "Azerty"; Allocating memory for strings
var o = {
A:1,
B:null
}; Allocating memory for an object object that contains a property value
var a = [1, NULL, "Abra"]; Allocating memory for an array that contains values
function f (a) {
return a + 2;
//To allocate memory for function (function is callable object)
Function expression is also an object, there is memory allocated
Someelement.addeventlistener (' click ', function () {
SomeElement.style.backgroundColor = ' Blue ';
}, False);

To complete an assignment through a function call
Some functions, when executed, also have an object allocation happening.
Copy Code code as follows:

var d = new Date ();
var e = document.createelement (' div '); Assigning a DOM element

Some methods assign new values or objects.
Copy Code code as follows:

var s = "Azerty";
var s2 = s.substr (0, 3); S2 is a new string
Because the string is invariant, JavaScript creates a new string for the contents of [0, 3] range
var a = ["Ouais Ouais", "Nan nan"];
var a2 = ["Generation", "Nan nan"];
var a3 = A.concat (A2); Combine a with A2 to produce a new array

The use of values
The use of values, in fact, is to perform read and write operations on the allocated memory. These actions include reading or writing to the properties of a variable or object, or passing arguments to a function.

free memory when it is no longer needed
The vast majority of memory management problems occur at this stage. The hardest thing to do is to determine how the allocated memory is no longer needed. This often requires a developer to decide when the program will no longer need memory and release the resources it occupies.

The high-level language parser embeds a program called "Garbage Collector", which is used to track the allocation and use of memory, to determine whether memory is needed, and to perform a resource release operation when it is no longer needed. He can only get an approximate value, because it is an indeterminate question to judge whether a memory is needed (it cannot be solved by an algorithm).

Garbage Collection
As mentioned above, we cannot accurately determine automatically that "memory is no longer needed." Therefore, garbage collection has limitations on the solution to the problem. This section explains the concepts necessary to understand the main garbage collection algorithms and their limitations.

Reference
One of the main concepts in garbage collection is references. In memory management, when an object uses another object either explicitly or implicitly, we say that he refers to another object. For example, a JavaScript object has an implicit reference to the stereotype, and a reference that explicitly points to his property value.

Here, the concept of objects goes beyond the concept of JavaScript in the traditional sense of objects, and includes function scopes and global scopes.

garbage collection using the reference counting algorithm
Here is an idealized algorithm that introduces the concept of "object no longer needed" and "no other object references that object." When the object's reference pointer changes to 0, it is assumed that he can be reclaimed.
Example:
Copy Code code as follows:

var o = {
A: {
B:2
}
}; Two objects were created. An object (a) is referenced by another object (an O-referenced object) and a as his property
The object is also referenced by the variable O
Obviously, no object can be recycled.
var O2 = O; The variable O2 references the object again
o = 1; o no longer references the object, only O2 is still referencing the object
var oa = o2.a; OA refers to O2 Property object A
The object is referenced by two other objects, which are O2 properties A and OA variables
O2 = "Yo"; The object is no longer referenced by another object, but his attribute A is still referenced by the OA variable, so he cannot be released.
OA = null; Now property A is no longer referenced by another object, and the object can be recycled

Restrictions: Looping
The algorithm has its limitations, when an object references another object, and when a circular reference is formed, they are no longer needed, and the garbage collector does not recycle them.
Copy Code code as follows:

function f () {
var o = {};
var O2 = {};
O.A = O2; o Reference O2
o2.a = O; O2 reference O
return "Azerty";
}
f ();
Two objects are created and form a reference to each other
After the function call ends, they will not break out of the function scope, although they will not be used, but will not be released
This is because the algorithm of the reference count determines that the object cannot be garbage collected as long as it has a referenced condition

Examples in the real world
In IE6, 7, a reference counting algorithm is used on a DOM object, where there is a memory leak problem.
Copy Code code as follows:

var div = document.createelement ("div");
Div.onclick = function () {
DoSomething ();
}; Div references an event handler through the Click Property
When the div variable is accessed in the event handler function, a circular reference is formed that will result in two objects not being reclaimed, resulting in a memory leak

mark-Purge algorithm
He introduced the concept of "object no longer needed" and "Object unreachable (Object unreachable)". The algorithm assumes a series of root objects (the root object in JavaScript is the global object), and every once in a while, the garbage collector starts with the root object, iterates through the objects that he references, and then iterates through the objects referenced by the object, and so on. In this way, the garbage collector can obtain all accessible objects and reclaim those that are inaccessible.
This algorithm is better than the previous algorithm, 0 referenced objects will be set to inaccessible objects, and he also avoids looping references caused by the annoying.
By 2012, most modern browsers used the "tag-purge algorithm" garbage collector. The JavaScript garbage collection domain (generation/increment/concurrency/parallel garbage collection) has improved the algorithms associated with it over the past few years, but the garbage collection algorithm itself (tag-purge algorithm) and "How to determine an object no longer needed" has not improved.

cycle is no longer a problem
In the first example, after the function call is finished, the two objects are not referenced by the global object or by the object referenced by the global object. Therefore, they are marked as inaccessible objects by the JavaScript garbage collector. This kind of thing also happens in the second example, when Div and event handlers are marked as inaccessible by the garbage collector, they are freed.

restrictions: Objects need to be explicitly marked as inaccessible
There are limitations to this method of tagging, but we are not exposed to him in programming, so we rarely care about garbage collection-related content.

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.