JS Memory Management

Source: Internet
Author: User

JS memory management, feel like JS in a door deputy head, we are usually not very loyal, but once the problem and very difficult, so you can learn a lot of JS in the memory management problems, in writing code through some of the usual habits, to avoid the problem of memory leaks.

In any language, the memory life cycle is basically the same:

1, allocating memory;

2, the use of allocated memory (read, write);

3, do not need to release memory.

In the C language, there is a dedicated memory management interface, like malloc () and free (). JS does not have a dedicated memory management interface, all the memory management is automatic. JS creates a variable that automatically allocates memory and automatically frees the memory when it is not in use. This automatic memory recovery has caused many JS developers not to care about memory recycling, which in fact causes many errors.

About JS Memory Recycling:

1. References:

The garbage collection algorithm relies primarily on the concept of reference, in a memory management environment where an object has permission to access another object (implicitly or explicitly), called an object that references another object. For example, a JavaScript object has a reference to its model (an implicit reference) and a reference to its properties (display reference)

2. Reference count garbage collection:

This is a simple garbage collection algorithm, this algorithm bar "whether the object is no longer required" is defined as "the object has no other object reference to it." If no reference object points to the object, the object is reclaimed by the garbage collection mechanism.

Example:

Let arr = [n/a];

arr = null;//[1,2,3] is not referenced at this time and will be automatically recycled

3: Limit: Cycle using:

In the following example, two objects are created and referenced to each other, resulting in a circular reference. They are called and do not leave the scope of the function, so they are useless and can be recycled, however, the reference counting algorithm considers that they have at least one reference to each other, so they will not be recycled.

Example:

function f () {

var x = {};

var y = {};

X.P = y;//x Reference y

Y.P = x;//y Reference x

A circular reference is formed here.

}

f ();

Practical Examples:

var Div;

Window.onload = function () {

div = document.getElementById ("MyId");

Div.circularreference = div;

Div.lotsofdata = new Array (10000). Join ("*");

};

In this example, the Circularreference attribute in the DOM element of myID references myID, resulting in a circular reference, ie6,7 garbage collection of DOM objects using reference counting, which often results in memory leaks when object references occur. The mainstream browser solves this problem by using the tag-clear memory recovery algorithm.

4: Mark-Sweep algorithm

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

This algorithm identifies an object called root root (in JS, the root is the global object). Periodically, the garbage collector starts at the root. Find all the objects that were consumed from the root, and then find the opposite of these object references, starting with the root, the garbage collector will find all the available objects and all the objects that are not available.

Since 2012, all major browsers have used the tag-clear memory recovery algorithm. All improvements to the JS garbage collection algorithm are based on this algorithm.

5: What's the memory leak?

Essentially, a memory leak is not the memory that is needed, and for some reason, it cannot be released.

6: Common Memory leak cases:

1: Global Variables:

function foo (ARG) {

Bar = "XX";

}

When working with an undeclared variable in JS, the bar in the example above is defined in the global object, on the browser, on the window. Global variables in the page will not be destroyed until the page is closed. So this kind of writing creates a memory leak, but letting this example leak is just a simple string, but in real-world code, things can get worse.

Another case where a global variable was created unexpectedly:

function foo () {

This.varl = "XX";

}

Foo ();

When Foo is called, this points to the global Variables window. A global variable was accidentally created, causing a memory leak.

We talked about some of the global variables defined in the unexpected case, and there are some global variables that we explicitly define in the code. If you use these global variables to stage large amounts of data, remember to re-assign them to null after use.

2: Non-destroyed timer and callback function:

In many libraries, if the observer pattern is used, a callback method is provided to invoke some callback functions for subsequent processing. Remember to reclaim these callback functions.

Give an example of a setinterval:

var serverdata = LoadData ();

SetInterval (function () {

var renderer = document.getElementById (' renderer ');

if (renderer) {

Renderer.innerhtml (Json.stringify (serverdata));

}

},5000);//5 second Call once

If the subsequent renderer element is overrun, the entire timer does not actually have any effect, but if you do not recycle it, the entire timer is still in memory, not only the timer cannot be recovered by the memory, but the dependencies in the timer function cannot be recycled. The serverdata in this case cannot be recycled either.

3. Closure Package:

In JS development, we often use closures, an intrinsic function that has access to variables in the outer function that contains it.

In this case, the closure can also cause a memory leak:

var thething = null;

var replacething = function () {

var originalthing = thething;

var unused = function () {

if (originalthing)//reference a variable in an external function that contains this function

Console.log ("X");

};

TheThing = {

Longstr:new Array (10000000). Join (' * '),

Somemethod:function () {

Console.log ("Y");

}

};

};

SetInterval (replacething,1000);

This code, each time replacething is called, thething gets the object containing a huge array and a somemethod for the new closure. At the same time unused is a closure that references the originalthing.

The key to this example is that the closure is a shared scope, although the unused may not have been called, but the SomeMethod may be called, causing the memory to not be recycled, and the memory will continue to grow when this code is executed repeatedly!

More description of the problem Courseware Meteor team article!

4. Dom Reference:

Many times we manipulate the DOM to save Don's references to an array or map

var elments = {

Image:document.getElementById ("image");

};

function Dostuff () {

ELEMENTS.IMAGE.SRC = ' http://example.com/image_name.png ';

}

function Removeimage () {
Document.body.removeChild (document.getElementById (' image '));
This time we still have a reference to the #image, the image element, still cannot be recycled by memory.
}
In the above case, even if we remove the image element, but still have a reference to the image element, we still cannot justify the memory reclamation.
Another point to note is the reference to the leaf node of a Dom tree. For example: if we refer to a TD element in a table, once we delete the entire table in the Dom, we intuitively feel that memory recycling should reclaim other elements besides the referenced TD. But in fact, this TD element is a child of the entire table and retains a reference to its parent element. This results in no memory reclamation for the entire table. So we have to be careful with references to Dom elements.
Intensive reading:
ES6 introduces the WeakSet and weakmap two new concepts to solve the memory recycling problems caused by references. WeakSet and Weakmap references to values are negligible, their references to values are weak references, and the memory-recycling mechanism does not consider such references. When other references are eliminated, the references are freed from memory.
JS this kind of high-level language, hiding the memory management function. But regardless of the developer's attention, memory management is there, and all programming languages end up dealing with the operating system, working on hardware with fixed memory size. Unfortunately, even without considering the impact of garbage collection on performance, the latest garbage collection algorithms in 2017 are not able to intelligently reclaim all extreme situations.
Only programmers know when to do garbage collection, and JS is not exposed to the display memory management interface, causing the code that triggers garbage collection to look like "junk", or the snippet that optimizes garbage collection looks elegant or even unreadable.
So in the high-level language such as JS, it is necessary to master the basic memory allocation principle, in the memory-sensitive scenarios, such as Nodejs code to do strict inspection and optimization. Use DOM operations with caution, proactively delete variables that do not have business meaning, avoid early optimizations, over-optimization, and use performance monitoring tools to locate problem codes through the call stack, while ensuring code readability.
At the same time, how to use the Chrome Debugging tools to analyze the memory leak methods and techniques. can refer to the Web front-end tutorial-intensive reading "2017 Front end performance Tuning Memo"
Summarize:
Even in JS, we seldom go directly to memory management. But when we write code, we also need to have memory management awareness, and carefully handle scenarios that can cause memory leaks.


Original link: https://juejin.im/entry/59f9331551882546b15bd2bd?utm_source=gold_browser_extension

JS Memory Management

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.