In trying to debug memory leaks in NodeJS, I’m finding it quite difficult (given the lack of profiling tools that I am aware of).
I thought I’d go back to basics and make sure I understand how a memory leak would be created specifically in NodeJS. I’m confused about the types of closures that might cause memory leaks and am unsure of what the garbage collector needs in order to free up that memory.
Could you give me some examples of basic patterns that would cause a memory leak in Node.js?
Not a “leak” exactly, but this can be a common pitfall.
This returns a function that references a scope, and every single local var in that scope will be kept, even though only one of those values are needed. This results in more memory usage than you need, especially if your function uses a small variable, but there are large values in that scope that you dont need to keep referencing.
How to fix it?
Simple option is to null out the variables you dont care about at the end of your function. The variables are still in scope, but their data would be released.
Or you could break anything that uses temp vars into it’s own function so their scopes can be released. This is a better solution for a larger project.