Home >Web Front-end >JS Tutorial >JavaScript prevents memory leaks
The running of the program requires memory. Whenever a program asks for it, the operating system or runtime must provide memory.
For a continuously running service process (daemon), memory that is no longer used must be released in a timely manner. Otherwise, the memory usage will become higher and higher, which will affect the system performance at best and cause the process to crash at worst.
Memory that is no longer used and is not released in time is called a memory leak.
Some languages (such as C language) must manually release memory, and the programmer is responsible for memory management.
char * buffer; buffer = (char*) malloc(42); // Do something with buffer free(buffer);
The above is 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. This is called a "garbage collector".
How does the garbage collection mechanism know which memory is no longer needed?
The most commonly used method is called "reference counting": the language engine has a "reference table" that saves the number of references to all resources (usually various values) in the memory. If the number of references to a value is 0, it means that the value is no longer used, so the memory can be released.
In the picture above, the two values in the lower left corner have no references, so they can be released.
If a value is no longer needed but the reference number is not 0, the garbage collection mechanism cannot release the memory, resulting in a memory leak.
const arr = [1, 2, 3, 4]; console.log('hello world');
In the above code, the array [1, 2, 3, 4] is a value and will occupy memory. The variable arr is the only reference to this value, so the number of references is 1. Although arr is not used in the following code, it will continue to occupy memory.
If you add a line of code to dereference arr to [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 above code, when arr is reset to null, the reference to [1, 2, 3, 4] is released, the number of references becomes 0, and the memory can be released.
Therefore, it does not mean that programmers will be relaxed with the garbage collection mechanism. You still need to pay attention to memory usage: those values that take up a lot of space, once they are no longer used, you have to check whether there are still references to them. If it is, you'll have to manually dereference it.
How can you observe a memory leak?
The rule of thumb is that if the memory usage becomes larger each time after five consecutive garbage collections, there is a memory leak. This requires real-time viewing of memory usage.
To check the memory usage of Chrome browser, follow the steps below.
Open the developer tools and select the Timeline panel
In the Capture field at the top, check Memory
Click the record button in the upper left corner.
Perform various operations on the page to simulate user usage.
After a period of time, click the stop button in the dialog box, and the memory usage during this period will be displayed on the panel.
If the memory usage is basically stable and close to level, it means there is no memory leak.
Otherwise, there is a memory leak.
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 containing the memory usage information of the Node process. This object contains four fields, the unit is bytes, the meaning is as follows.
rss (resident set size): All memory usage, including instruction area and stack.
heapTotal:"堆"占用的内存,包括用到的和没用到的。
heapUsed:用到的堆的部分。
external: V8 引擎内部的 C++ 对象占用的内存。
判断内存泄漏,以heapUsed字段为准。
前面说过,及时清除引用非常重要。但是,你不可能记得那么多,有时候一疏忽就忘了,所以才有那么多内存泄漏。
最好能有一种方法,在新建引用的时候就声明,哪些引用必须手动清除,哪些引用可以忽略不计,当其他引用消失以后,垃圾回收机制就可以释放内存。这样就能大大减轻程序员的负担,你只要清除主要引用就可以了。
ES6 考虑到了这一点,推出了两种新的数据结构:WeakSet 和 WeakMap。它们对于值的引用都是不计入垃圾回收机制的,所以名字里面才会有一个"Weak",表示这是弱引用。
下面以 WeakMap 为例,看看它是怎么解决内存泄漏的。
const wm = new WeakMap(); const element = document.getElementById('example'); wm.set(element, 'some information'); wm.get(element) // "some information"
上面代码中,先新建一个 Weakmap 实例。然后,将一个 DOM 节点作为键名存入该实例,并将一些附加信息作为键值,一起存放在 WeakMap 里面。这时,WeakMap 里面对element的引用就是弱引用,不会被计入垃圾回收机制。
也就是说,DOM 节点对象的引用计数是1,而不是2。这时,一旦消除对该节点的引用,它占用的内存就会被垃圾回收机制释放。Weakmap 保存的这个键值对,也会自动消失。
基本上,如果你要往对象上添加数据,又不想干扰垃圾回收机制,就可以使用 WeakMap。
WeakMap 的例子很难演示,因为无法观察它里面的引用会自动消失。此时,其他引用都解除了,已经没有引用指向 WeakMap 的键名了,导致无法证实那个键名是不是存在。
我一直想不出办法,直到有一天贺师俊老师提示,如果引用所指向的值占用特别多的内存,就可以通过process.memoryUsage方法看出来。
根据这个思路,网友 vtxf 补充了下面的例子。
首先,打开 Node 命令行。
$ node --expose-gc
上面代码中,--expose-gc参数表示允许手动执行垃圾回收机制。
然后,执行下面的代码。
// 手动执行一次垃圾回收,保证获取的内存使用状态准确 > global.gc(); undefined // 查看内存占用的初始状态,heapUsed 为 4M 左右 > process.memoryUsage(); { rss: 21106688, heapTotal: 7376896, heapUsed: 4153936, external: 9059 } > let wm = new WeakMap(); undefined > const b = new Object(); undefined > global.gc(); undefined // 此时,heapUsed 仍然为 4M 左右 > process.memoryUsage(); { rss: 20537344, heapTotal: 9474048, heapUsed: 3967272, external: 8993 } // 在 WeakMap 中添加一个键值对, // 键名为对象 b,键值为一个 5*1024*1024 的数组 > wm.set(b, new Array(5*1024*1024)); WeakMap {} // 手动执行一次垃圾回收 > global.gc(); undefined // 此时,heapUsed 为 45M 左右 > process.memoryUsage(); { rss: 62652416, heapTotal: 51437568, heapUsed: 45911664, external: 8951 } // 解除对象 b 的引用 > b = null; null // 再次执行垃圾回收 > global.gc(); undefined // 解除 b 的引用以后,heapUsed 变回 4M 左右 // 说明 WeakMap 中的那个长度为 5*1024*1024 的数组被销毁了 > process.memoryUsage(); { rss: 20639744, heapTotal: 8425472, heapUsed: 3979792, external: 8956 }
上面代码中,只要外部的引用消失,WeakMap 内部的引用,就会自动被垃圾回收清除。由此可见,有了它的帮助,解决内存泄漏就会简单很多。
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 prevents memory leaks. For more information, please follow other related articles on the PHP Chinese website!