JavaScript prevents Memory leakage

Source: Internet
Author: User
For continuous running service processes (daemon), the memory that is no longer used must be released in a timely manner. Otherwise, the memory usage is getting higher and higher, which affects the system performance and causes the process to crash. 1. What is memory leakage?

The program requires memory to run. As long as the program requests, the operating system or runtime must supply the memory.

For continuous running service processes (daemon), the memory that is no longer used must be released in a timely manner. Otherwise, the memory usage is getting higher and higher, which affects the system performance and causes the process to crash.

Memory leakage is called memory leak ).

Some languages (such as C Language) must manually release the memory, and programmers are responsible for memory management.

char * buffer;buffer = (char*) malloc(42);// Do something with bufferfree(buffer);

The above is the C-language code. The malloc method is used to apply for memory. after use, you must use the free method to release the memory.

This is troublesome, so most languages provide automatic memory management to reduce the burden on programmers, known as the "garbage collection mechanism" (garbage collector ).

Ii. Garbage Collection Mechanism

How does the garbage collection mechanism know which memory is no longer needed?

The most commonly used method is reference counting. The language engine has a reference table that stores all resources in the memory (usually various values). If the number of times a value is referenced is 0, it indicates that the value is no longer used, so the memory can be released.

And the two values in the lower left corner. No reference is available. Therefore, it can be released.

If a value is no longer needed, but the number of references is not 0, the garbage collection mechanism cannot release this memory, resulting in Memory leakage.

const arr = [1, 2, 3, 4];console.log('hello world');

In the code above, the array [1, 2, 3, 4] is a value that occupies memory. The variable arr is the only reference to this value, so the number of references is 1. Although the Code below does not use arr, it will continue to occupy the memory.

If you add a line of code to remove the reference from the arr pair [1, 2, 3, 4], this memory can be released by the garbage collection mechanism.

const arr = [1, 2, 3, 4];console.log('hello world');arr = null;

In the code above, when arr is reset to null, the reference to [1, 2, 3, 4] is removed, and the number of references is changed to 0, so that the memory can be released.

Therefore, it does not mean that programmers can easily use the garbage collection mechanism. You still need to pay attention to memory usage: for those very space-consuming values, once they are no longer used, you must check whether there are still references to them. If yes, you must manually release the reference.

Iii. Memory leakage Identification Method

How can we observe the memory leakage?

The rule of thumb is that if the memory usage is larger after five consecutive garbage collection times, there will be Memory leakage. This requires you to view the memory usage in real time.

3.1 Browser

To view memory usage in Chrome, follow these steps.

  1. Open the developer tool and select the Timeline panel.


  2. Select Memory in the Capture field at the top.


  3. Click the recording button in the upper left corner.


  4. Perform Various operations on the page to simulate user usage.


  5. After a period of time, click the stop button in the dialog box to display the memory usage during this period.


If the memory usage is stable and close to the horizontal level, there is no memory leakage.

On the contrary, memory leakage occurs.

3.2 command line

The command line can use the process. memoryUsage method provided by Node.

console.log(process.memoryUsage());// { rss: 27709440,//  heapTotal: 5685248,//  heapUsed: 3449392,//  external: 8772 }

Process. memoryUsage returns an object that contains the memory usage information of the Node process. The object contains four fields, in bytes.

  • Rss (resident set size): memory usage, including command area and stack.


  • HeapTotal: Memory occupied by "Heap", including used and useless.


  • HeapUsed: the heap used.


  • External: Memory occupied by C ++ objects in the V8 engine.


Determine the memory leakage. The heapUsed field prevails.

4. WeakMap

As mentioned earlier, it is very important to clear references in a timely manner. However, you cannot remember so much. Sometimes you forget it when you neglect it, so there is so much memory leakage.

There is a better way to declare when creating a reference, which references must be manually cleared and which references are negligible. When other references disappear, the garbage collection mechanism can release the memory. This will greatly reduce the burden on programmers. You only need to clear the main references.

ES6 considers this and introduces two new data structures: WeakSet and WeakMap. Their reference to values is not included in the garbage collection mechanism, so there is a "Weak" in the name, indicating that this is a Weak reference.

The following uses WeakMap as an example to see how it solves Memory leakage.

const wm = new WeakMap();const element = document.getElementById('example');wm.set(element, 'some information');wm.get(element) // "some information"

In the above Code, create a new Weakmap instance. Then, a DOM node is saved to the instance as the key name, and some additional information is stored in WeakMap as the key value. In this case, the element references in WeakMap are weak references and will not be included in the garbage collection mechanism.

That is to say, the reference count of the DOM Node object is 1, not 2. At this time, the memory occupied by the node will be released by the garbage collection mechanism once the reference to the node is eliminated. The key-Value Pair saved by Weakmap will also disappear automatically.

Basically, if you want to add data to an object without interfering with the garbage collection mechanism, you can use WeakMap.

V. WeakMap example

The example of WeakMap is difficult to demonstrate because the reference in WeakMap will disappear automatically. In this case, all the other references are removed and no reference is made to the WeakMap key name. As a result, it cannot be confirmed whether the key name exists.

I couldn't find a solution until one day, teacher he Shijun suggested that if the referenced value occupies a very large amount of memory, you can see it through the process. memoryUsage method.

According to this idea, the netizen vtxf adds the following example.

First, open the Node command line.

$ node --expose-gc

In the above Code, the -- expose-gc parameter indicates that manual garbage collection is allowed.

Then, execute the following code.

// Manually execute a garbage collection task to ensure that the obtained memory usage status is accurate> global. gc (); undefined // check the initial state of memory usage. The heapUsed is about 4 MB> process. memoryUsage (); {rss: 21106688, heapTotal: 7376896, heapUsed: 4153936, external: 9059}> let wm = new WeakMap (); undefined> const B = new Object (); undefined> global. gc (); undefined // at this time, heapUsed is still about 4 M> process. memoryUsage (); {rss: 20537344, heapTotal: 9474048, heapUsed: 3967272, external: 8993} // Add a key-value pair to WeakMap. // The key name is object B, the key value is an array of 5*1024*1024> wm. set (B, new Array (5*1024*1024); WeakMap {}// manually execute a garbage collection> global. gc (); undefined // at this time, heapUsed is about 45 M> process. memoryUsage (); {rss: 62652416, heapTotal: 51437568, heapUsed: 45911664, external: 8951} // unreference object B> B = null; null // execute garbage collection again> global. gc (); undefined // After B is removed, heapUsed is changed back to around 4 M. // The array with a length of 5*1024*1024 in WeakMap is destroyed> process. memoryUsage (); {rss: 20639744, heapTotal: 8425472, heapUsed: 3979792, external: 8956}

In the above Code, as long as the external reference disappears, the Reference inside WeakMap will be automatically cleared by garbage collection. It can be seen that with its help, it will be much easier to solve Memory leakage.

6. Reference Links
  • Simple Guide to Finding a JavaScript Memory Leak in Node. js


  • Understanding Garbage Collection and hunting Memory Leaks in Node. js


  • Debugging Memory Leaks in Node. js Applications

The above is the detailed content of JavaScript to prevent memory leakage. For more information, see other related articles in the first PHP community!

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.