JavaScript memory Management

Source: Internet
Author: User

Brief introduction

JavaScript allocates memory when variables (objects, strings, and so on) are created, and then "automatically" releases them when they are no longer in use. The latter is known as garbage collection . The word "auto" is confusing, confusing, and gives JavaScript (and other high-level language) developers an impression that they don't have to think about memory management. However, this is wrong.

Memory Life cycle

Regardless of programming language, the memory life cycle is basically consistent:

    1. Allocate the memory you need
    2. Use allocated memory (read, write)
    3. Release it when it is not needed \ return it

In all languages the first and second parts are clear. The final step is clear in low-level languages, but in high-level languages like JavaScript, this step is hidden.

Initialization of memory allocation values for JavaScript

To keep programmers from allocating memory, JavaScript completes memory allocations when defining variables

Allocates memory var n = 123 for numeric variables; Allocates memory to a string var s = "Azerty"; Allocates memory for the object and its containing value var o = {  a:1,  b:null};//Allocates memory for the array and its contained values (just like an object) var a = [1, NULL, "Abra"];//assign Memory fun to functions (callable objects) Ction F (a) {  return a + 2;}//function expression can also be assigned an object Someelement.addeventlistener (' click ', Function () {  SomeElement.style.backgroundColor = ' blue ';}, False);
Memory allocations through function calls

Some function call results are allocated object memory:

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

Some methods assign new variables or new objects:

var s = "Azerty"; var s2 = s.substr (0, 3); S2 is a new string//Because the string is invariant//JavaScript may not allocate memory//But only stores a range of [0-3]. var a = ["Ouais Ouais", "Nan nan"];var a2 = ["Generation", "Nan nan"];var a3 = A.concat (A2); The new array has four elements, which is the result of a connection A2
Use of values

The process of using a value is actually a read-write operation on the allocated memory. Reading and writing can be written to a variable or to an object's property value, or even to the arguments of a function.

Release when memory is no longer required to be used

Most of the memory management problems are at this stage. The hardest task here is to find "the allocated memory is no longer needed." It often requires the developer to determine which piece of memory in the program is no longer needed and frees it.

The high-level language interpreter embeds the garbage collector, and its primary work is to track the allocation and use of memory so that it is automatically freed when the allocated memory is no longer in use. This can only be an approximate process, because it is not possible to know if a block of memory is still needed (it cannot be solved by an algorithm).

Garbage collection

As mentioned above, it is not possible to automatically find out if some memory "no longer needed" problem is determined. Therefore, garbage collection implementations can only have a limited solution to general problems. This section explains the concepts necessary to understand the main garbage collection algorithms and their limitations.

Reference

The garbage collection algorithm relies primarily on the concept of references . In a memory-managed environment, an object that has permission to access another object (implicitly or explicitly) is called an object that references another object. For example, a JavaScript object has a reference to its prototype (an implicit reference) and a reference to its properties (an explicit reference).

Here, the concept of "object" refers not only to JavaScript objects, but also to function scopes (or global lexical scopes).

Reference count Garbage collection

This is the simplest garbage collection algorithm. This algorithm defines whether the object no longer needs to be simplified as "object has no other object referenced to it". If no references point to the object (0 references), the object is reclaimed by the garbage collection mechanism.

For example
var o = {   A: {    b:2  }};//Two objects are created, one is referenced as another property, and the other is assigned to a variable o//Obviously, no one can be garbage collected var O2 = O;//O2 variable is a second reference to "this object" O = 1;      Now, the original reference o to "this object" was replaced by o2 var OA = o2.a; Refer to the A property of "this object"///Now, "This object" has two references, one is O2, one is Oao2 = "Yo"; The original object is now 0 references           //he can be garbage collected//           however its property a object is still referenced by OA, so it is not possible to reclaim OA = NULL;//The object of a property is now 0 references           //It can be garbage collected
Restrictions: Circular references

One limitation of this simple algorithm is that if one object refers to another (which forms a circular reference), they may "no longer need", but they will not be recycled.

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 referenced to each other, forming a loop//they are called and do not leave the function scope//So they have no use, can be recycled//However, the reference counting algorithm takes into account that they have at least one reference to each other, so they will not be recycled
Practical examples

IE 6, 7 reference count collection for DOM objects. For them, a common problem is memory leaks:

var div = document.createelement ("div");d Iv.onclick = function () {  dosomething ();};//div has a reference to the event handling property onclick// Event handling also has a reference to the div that can be accessed in the function scope//This circular reference causes two objects to not be garbage collected
Tag-Purge algorithm

This algorithm simplifies the definition of "whether an object is no longer needed" as "whether an object is available."

The algorithm assumes that an object called the root is set (in JavaScript, the root is the global object). Periodically, the garbage collector starts from the root, looking for all objects referenced from the root, and then looking for objects referenced by those objects ... Starting at the root, the garbage collector will find all available objects and all objects that are not available.

This algorithm is better than the previous one because "objects with 0 references" are not always available, but not necessarily, refer to "circular references".

Since 2012, all modern browsers have used the tag-clear garbage collection algorithm. All of the improvements to the JavaScript garbage collection algorithm are based on the improvement of the tag-purge algorithm, and there is no improvement to the markup-purge algorithm itself and its simplified definition of whether the object is no longer needed.

Circular references are no longer a problem in the above example, after the function call returns, two objects cannot be retrieved from the global object. As a result, they will be recycled by the garbage collector.

The second example also, once the div and its event processing cannot be obtained from the root, they will be reclaimed by the garbage collector

Limitations: Objects that cannot be queried from the root object will be purged

Although this is a limitation, in practice we rarely encounter a similar situation, so developers are less likely to care about garbage collection mechanisms.

Reference
    • IBM article on "Memory leak patterns in JavaScript" (2007)
    • Kangax article on what to register event handler and avoid memory leaks (2010)
    • Performance

JavaScript memory Management

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.