This is the 17th day of my participation in the August Text Challenge.More challenges in August
This is the last article in the memory control section, troubleshooting memory leaks
- Article 1: V8’s memory limitations and why
- Chapter two: V8’s garbage collection mechanism
- Article 3: Efficient Use of Memory
- Part four: Memory metrics
- Part 5: Causes and Solutions to memory leaks
The last article talked about the causes and solutions of memory leakage. One is to treat memory as a cache. The cache object will be resident in the old generation, so it is necessary to limit the number of cache object keys. Second, in the producer-consumer model, if the production speed is much faster than consumption, memory leakage will be caused, and timeout alarm needs to be set, or reject mode is adopted.
This article introduces the tool: Node-heapdump
node-heapdump
Let’s try node-heapdump as follows:
Start by initializing a test project
mkdir test_memory_leak
cd test_memory_leak
npm init
...
touch index.js
Copy the code
Ready to test the code, we will push elements to the leakArray array every time we visit http://127.0.0.1:1337/ and the memory will not be freed
var http = require('http');
var leakArray = [];
var leak = function () {
leakArray.push("leak" + Math.random());
};
http.createServer(function (req, res) {
leak();
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/);
console.log(process.pid);
Copy the code
Installation node – heapdumps
npm i heapdump
Copy the code
Add to the first line of index.js
var heapdump = require('heapdump');
Copy the code
Repeated requests for our address using the AB (Apache Bench) tool caused a memory leak
Ab - n 3000 http://127.0.0.1:1337/Copy the code
By sending SIGUSR2 signals to the server process, node-heapdump captures a memory snapshot where the PID has been printed by process.pid
kill -USR2 <pid>
Copy the code
This snapshot is in the project directory as heapdump-.. Heapsnapshot format, which is a large JSON file that needs to be viewed through chrome Developer Tools
Go into Memory, right-click on the left and select Load
Select the file you just generated
You can see a lot of leak strings that aren’t recycled
You can check for memory leaks by resident the memory with leak strings
Node-heapdump is a memory leak detection method