a blog for those who code

Monday, 28 September 2015

How to detect memory leak in NodeJS

In this post we are going to discuss about detecting memory leaks in Node.js. Memory leak is the process of gradual loss of available computer memory when a program repeatedly fails to return memory that it has obtained.


The following tools will help you to spot memory leaks :

node-inspector : Node Inspector is a debugger interface for Node.js applications that uses the Blink Developer Tools

memwatch : node-memwatch is here to help you detect and find memory leaks in Node.JS code. It provides a leak event (emitted when it appers your code is leaking memory), a stats event (emitted occasionaly, giving you data describing your heap usage and trends over time) and a HeapDiff class (lets you compare the state of your heap between two points in time, telling you what has been allocated, and what has been released).

mtrace : Native memory allocation tracing and mtrace log parsing for node. It is only supported in Linux.

heapdump : It makes a dump of V8 heap for later inspection.

webkit-devtools-agent : It leverages remote debugging and profiling of nodejs applications using the built-in webkit inspector.

Memory Leak example in Nodejs

Example 1 : We have a class called MyClass that simply adds 100 objects into an array every second.

function MyClass() {}

var arr = [];
setInterval(function() {
  for(var i = 0; i < 100; i++) {
    arr.push(new MyClass);
  }
}, 1000);

Example 2 : In this example every request adds up another 1000 function (func()).

var server = http.createServer(function (request, response) {
  for(var i = 0; i < 1000; i++) {
    server.on('request', function func() {
      //leaky function
    });
  }
  response.end('Hello World');
}).listen(8089);

These two examples are the perfect example of memory leaks in Nodejs and using the above methods you can easily detect memory leaks. Like for the first example node-inspector will show you memory leak as shown below.


Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

1 comment:

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License