JavaScript Learning Summary (23)--javascript Memory leak tutorial

Source: Internet
Author: User

Reference Tutorial: Http://www.ruanyifeng.com/blog/2017/04/memory-leak.html What is a memory leak?

The operation of the program requires memory. The operating system or runtime (runtime) must supply memory whenever the program requests it.

For a continuously running service process (daemon), the memory that is no longer used must be released in a timely manner. Otherwise, the memory footprint is increasing and the light affects system performance, which causes the process to crash.

Memory that is no longer used, is not released in time, is called a memory leak (leak).

Some languages (such as C) must manually free up memory and the programmer is responsible for memory management.

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

Above is the C language code, the malloc method used to request memory, after use, you must use the free method to free memory.

This is cumbersome, so most languages offer automatic memory management, reducing the burden on programmers, which is known as the "garbage collection mechanism" (garbage collector).

Second, the garbage collection mechanism

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

The most commonly used method is called "reference count" (reference counting): The language engine has a "reference table" that holds the number of references to all resources (usually various values) in memory. If the number of references to a value is 0 , it means that the value is no longer used, so you can release the memory.

, two values in the lower-left corner, without any references, can be freed.

If a value is no longer needed and the number of references is not 0 , the garbage collection mechanism cannot release the memory, causing a memory leak.

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

In the above code, the array [1, 2, 3, 4] is a value that consumes memory. arrA variable is the only reference to this value, so the number of references is 1 . Although the latter code is not used arr , it will continue to consume memory.

If you add a line of code, release arr for [1, 2, 3, 4] references, this memory can be freed by the garbage collection mechanism.

let Arr = [123< Span class= "token punctuation", 4];console. Log (;arr = null              

In the above code, reset arr to null , the reference is lifted, the number of [1, 2, 3, 4] references becomes 0 , memory can be released.

Therefore, it is not that there is a garbage collection mechanism, the programmer is easy. You still need to focus on memory consumption: those that occupy a lot of space, and once they are no longer used, you have to check if there are any references to them. If so, you must remove the reference manually.

Three, the memory leak recognition method

How can a memory leak be observed?

The rule of thumb is that if the memory footprint is larger than once for five successive garbage collections, there is a memory leak. This requires a real-time view of the memory footprint.

3.1 Browser

Chrome Browser View memory consumption, follow the steps below.

  1. Open developer tools and select Timeline Panel
  2. Tick the Memory in the top Capture field
  3. Click the Record button in the upper-left corner.
  4. Perform various actions on the page to simulate user usage.
  5. After a while, click the Stop button in the dialog box, and the panel will show the memory footprint for this time period.

If the memory footprint is basically smooth and close to the level, it means there is no memory leak.

Conversely, it is a memory leak.

3.2 Command Line

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

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

process.memoryUsageReturns an object that contains the memory footprint information for the Node process. The object contains four fields, in bytes, meaning the following.

  • RSS (resident set size): All memory consumption, including the instruction area and stack.
  • Heaptotal: Memory occupied by "heap", including used and useless.
  • Heapused: The part of the heap to use.
  • External:v8 the memory occupied by C + + objects inside the engine.

Determine the memory leak, heapUsed whichever is the field.

Iv. Weakmap

As I said earlier, it is important to clear the references in a timely manner. But you can't remember that much, and sometimes you forget about it, so there are so many memory leaks.

It is best to have a method that declares when a new reference is made, which references must be manually cleared, which references are negligible, and the garbage collection mechanism can free memory when other references disappear. This can greatly reduce the burden on the programmer, you just need to clear the main reference.

ES6 with this in mind, two new data structures have been introduced: WeakSet and Weakmap. Their reference to the value is not counted as garbage collection, so there is a "Weak" in the name, indicating that it is a weak reference.

Let's take weakmap as an example to see how it solves a memory leak.

Const WM=NewWeakmap (;const Element = document. Getelementbyid ( ' example ' ;wm.set (Element ' some information ' ) ;wm. get (Element          

In the above code, create a new Weakmap instance first. A DOM node is then stored as a key name in the instance, and some additional information is stored in the Weakmap as a key value. At this point, the reference inside the Weakmap element is a weak reference and will not be counted as a garbage collection mechanism.

That is, the reference count of the DOM node object is 1 , not 2 . At this point, once the reference to the node is eliminated, the memory it consumes is freed by the garbage collection mechanism. This key-value pair saved by Weakmap will also disappear automatically.

Basically, if you want to add data to an object and don't want to interfere with the garbage collection mechanism, you can use Weakmap.

V. Examples of WEAKMAP

The Weakmap example is difficult to demonstrate because it is not possible to see the references in it automatically disappear. At this point, the other references are dismissed, and no reference to the key name of the Weakmap has been made, resulting in an inability to verify that the key name exists.

I couldn't think of a way to do it until one day He Shijun teacher suggests that if the reference points to a value that takes up a lot of memory, you can process.memoryUsage see it through the method.

According to this idea, Netizen VTXF added the following example.

First, open the Node command line.

--expose-gc

In the above code, the --expose-gc parameter indicates that the garbage collection mechanism is allowed to be performed manually.

Then, execute the following code.

Perform a garbage collection manually to ensure that the acquired memory usage status is accurate> Global.Gc(); UndefinedView the initial state of memory consumption, heapused to about 4M> Process.Memoryusage();{RSS:21106688, Heaptotal:7376896, heapused:4153936, external:9059}>Let WM=NewWeakmap(); undefined>Let B=NewObject(); undefined> Global.Gc(); undefinedAt this point, heapused is still around 4M> Process.Memoryusage();{RSS:20537344, Heaptotal:9474048, heapused:3967272, external:8993}Add a key-value pair in the Weakmap,The key name is Object B, and the key value is an array of 5*1024*1024> WM.Set(b,NewArray(5*1024*1024)); Weakmap{}To perform a garbage collection manually> Global.Gc(); undefinedAt this time, heapused is about 45M> Process.Memoryusage();{RSS:62652416, Heaptotal:51437568, heapused:45911664, external:8951}To dismiss a reference to object B> b=Null;NullPerform garbage collection again> Global.Gc(); undefined//release B after the reference, heapused change back to around 4M //description weakmap the length of 5*1024*1024 The array was destroyed > process. Memoryusage{rss: 20639744842547239797928956 "              

In the above code, as long as the external reference disappears, Weakmap internal references are automatically purged by garbage collection. This shows that with its help, it is much easier to solve a memory leak.

Vi. Reference Links
    • 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

JavaScript Learning Summary (23)--javascript Memory leak tutorial

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.