1. What is a memory leak?
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".
2. Garbage collection mechanism
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.
3. How to identify memory leaks
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.
3.1 Browser
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.
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 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字段为准。
四、WeakMap
前面说过,及时清除引用非常重要。但是,你不可能记得那么多,有时候一疏忽就忘了,所以才有那么多内存泄漏。
最好能有一种方法,在新建引用的时候就声明,哪些引用必须手动清除,哪些引用可以忽略不计,当其他引用消失以后,垃圾回收机制就可以释放内存。这样就能大大减轻程序员的负担,你只要清除主要引用就可以了。
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 的例子很难演示,因为无法观察它里面的引用会自动消失。此时,其他引用都解除了,已经没有引用指向 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!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
