This question asks about something similar. Essentially, the idea is that if you use closure in a callback, you must unsubscribe from the callback when you're done so that the GC knows that it cannot be called again. It makes sense to me; if you have a circuit waiting for a call, it will be difficult for the GC to know that you are done with it. By manually removing the closure from the callback mechanism, it becomes unconnected and available for collection.
In addition, Mozilla published an excellent article on finding memory leaks in Node.js. I assume that if you try some of their strategies, you may find parts of your code that express a leak. Best practices are good and all, but I think it’s more useful to understand the needs of your program and come up with some personalized best practices based on what you can observe empirically.
Here is a brief excerpt from an article on Mozilla:
- Jimb Essers
node-mtrace , which uses the GCC mtrace utility to profile heap usage. - Dave Pachecos
node-heap-dump takes a snapshot of the V8 heap and serializes it all into a huge JSON file. It includes tools for viewing and examining the resulting snapshot in JavaScript. - Danny Coatess
v8-profiler and node-inspector provide Node bindings for the V8 profiler and Node debugging interface using WebKit Web Inspector. - Felix Gnasss from the same fork that disables the latch graph
- The Felix Geisendörfers node memory leak tutorial is a short and enjoyable explanation of how to use
v8-profiler and node-debugger , and is currently up-to-date for debugging most memory leaks in Node.js. - The Joyents SmartOS platform, which provides you with an arsenal of tools for troubleshooting memory leaks in Node.js.
The answers to this question basically say that you can help the GC by setting null to closure variables.
var closureVar = {}; doWork(function callback() { var data = closureVar.usefulData;
Any variables declared inside the function will disappear when the function returns, except for those used in other closures. In this example, closureVar should be in memory before callback() , but who knows when this will happen? After the callback has been called, you can give a hint to 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 outdated and inconsequential for Node.js. I do not have a final answer to this question; I just publish what I found on the network.
RustyTheBoyRobot Oct 30 '13 at 14:47 2013-10-30 14:47
source share