You quite often read on the web that using closures is a massive source of memory leaks in JavaScript. Most of the times these articles refer to mixing script code and DOM e
You can find a good example and explanation in this blog post by David Glasser.
Well, here it is (I added a few comments):
var theThing = null;
var cnt = 0; // helps us to differentiate the leaked objects in the debugger
var replaceThing = function () {
var originalThing = theThing;
var unused = function () {
if (originalThing) // originalThing is used in the closure and hence ends up in the lexical environment shared by all closures in that scope
console.log("hi");
};
// originalThing = null; // <- nulling originalThing here tells V8 gc to collect it
theThing = {
longStr: (++cnt) + '_' + (new Array(1000000).join('*')),
someMethod: function () { // if not nulled, original thing is now attached to someMethod -> <function scope> -> Closure
console.log(someMessage);
}
};
};
setInterval(replaceThing, 1000);
Please try it out with and without nulling originalThing
in Chrome Dev Tools (timeline tab, memory view, click record). Note that the example above applies to browser and Node.js environments.
Credit also and especially to Vyacheslav Egorov.
This question asks about something similar. Basically, the idea is that if you use a closure in a callback, you should "unsubscribe" the callback when you are finished so the GC know that it can't be called again. This makes sense to me; if you have a closure just waiting around to be called, the GC will have a hard time knowing that you're finished with it. By manually removing the closure from the callback mechanism, it becomes unreferenced and available for collection.
Also, Mozilla has published a great article on finding memory leaks in Node.js code. I would assume that if you try out some of their strategies, you could find parts of your code that express leaky behavior. Best practices are nice and all, but I think it's more helpful to understand your program's needs and come up with some personalized best practices based on what you can empirically observe.
Here's a quick excerpt from the Mozilla article:
- Jimb Esser’s
node-mtrace
, which uses the GCCmtrace
utility to profile heap usage.- Dave Pacheco’s
node-heap-dump
takes a snapshot of the V8 heap and serializes the whole thing out in a huge JSON file. It includes tools to traverse and investigate the resulting snapshot in JavaScript.- Danny Coates’s
v8-profiler
andnode-inspector
provide Node bindings for the V8 profiler and a Node debugging interface using the WebKit Web Inspector.- Felix Gnass’s fork of the same that un-disables the retainers graph
- Felix Geisendörfer’s Node Memory Leak Tutorial is a short and sweet explanation of how to use the
v8-profiler
andnode-debugger
, and is presently the state-of-the-art for most Node.js memory leak debugging.- Joyent’s SmartOS platform, which furnishes an arsenal of tools at your disposal for debugging Node.js memory leaks
The answers to this question basically say that you can help the GC out by assigning null
to closure variables.
var closureVar = {};
doWork(function callback() {
var data = closureVar.usefulData;
// Do a bunch of work
closureVar = null;
});
Any variables declared inside a function will go away when the function returns, except those that are used in other closures. In this example, closureVar
has to be in memory until callback()
is called, but who knows when that will happen? Once the callback has been called, you can give a hint to the GC by setting your closure variable to null.
DISCLAIMER: As you can see from the comments below, there are some SO users who say that this information is out of date and inconsequential for Node.js. I don't have a definitive answer on that yet; I'm just posting what I've found on the web.
I have to disagree with closures being a cause of memory leaks. This maybe true for older versions of IE because of its shoddy garbage collection. Please read this article from Douglas Crockford, which clearly states what a memory leak is.
The memory that is not reclaimed is said to have leaked.
Leaks are not the problem, efficient garbage collection is. Leaks can happen in both browser and server JavaScript applications alike. Take V8 as an example. In the browser, garbage collection happens on a tab when you switch to different window/tab. The leak is plugged when idle. Tabs can be idle.
On the server things are not so easy. Leaks can happen, but GC is not as cost-effective. Servers cannot afford to GC frequently or its performance will be affected. When a node process reaches a certain memory usage, it kicks in the GC. Leaks will then be removed periodically. But leaks still can happen at a faster rate, causing programs to crash.