0

I'm currently researching why our nodejs app is leaking memory. I'm not a very skilled nodejs programmer (I usually work with C#) so I'm trying to read as much documentation as I can on this subject to find cause and solution.

This question and mostly this blogpost have taught me about the dangers of closures. Our code is full of closures so I'm trying to analyze whether the situation mentioned in these two links apply.

And then there is the habit in many javascript code to write "var self = this;" when using closures, as for example explained here. A "feature" called lexical closure. This is also used abundantly in our code.

So my question is, if you use this lexical closure technique but you don't set self to null at the end of your function, are you leaking self/this?

To give a concrete example, does this function cause a leak:

Achievement.INSERT_QUERY = "SOME QUERY";
Achievement.prototype.insert = function(child, achievement){
    var self = this;
    var data = [child, achievement];
    return this._query(Achievement.INSERT_QUERY, data, function insertResultHandler(err, result){
        if(err) {
            self.emit(DB.ERROR, err);
            return false;
        }
        self.emit(DB.UPDATED, data);
    });
}

Many thanks for any clarification!

Community
  • 1
  • 1
ava
  • 71
  • 1
  • 5
  • that alone should not be leaking; local vars (incl closures) are discarded when no longer reachable. if the callback is not consumed/triggered, then maybe. if in doubt, you can pass `self.emit.bind(self)` instead of the whole object. – dandavis Feb 03 '16 at 20:29
  • Ok, and then, since self is discarded, there won't be any lingering references to 'this'. But if I replaced 'this' with 'anObject' and declare var anObject = {}; outside the function, it would leak? – ava Feb 03 '16 at 20:40
  • i don't think that's a leak because there would only be one outside object used by all invocations, and the local `self` reference would still be discarded. – dandavis Feb 03 '16 at 21:27
  • As already said, this won't be a memory leak. Just an idea: You are not storing expressJS sessions in-memory, are you? Because that could be a very, very good way of leaking memory. – alsdkjasdlkja Feb 04 '16 at 03:21

0 Answers0