Alvin Cao
Alvin Cao

Reputation: 577

Is this nodejs code a circular reference?

They are just a few lines from node.js official documents.

client.on('data', function(data) {
  console.log(data.toString());
  client.end();
});

I think client object has reference to the callback, the callback has a closure reference to client object. Is that correct? If yes, why is this encouraged?

Upvotes: 2

Views: 1109

Answers (2)

Peter Lyons
Peter Lyons

Reputation: 146084

Yes, this is a circular reference, but it is not a memory leak. Given just this code snippet, you only have a small graph of a handful of objects, but yes, as long as client is reachable from your main program, all of these objects will never be eligible for garbage collection. However, if you were to set client = null;, The graph of objects including the client object and the anonymous event handler function would be unreachable from the main program and thus eligible for garbage collection and thus A-OK.

This pattern in and of itself is not a memory leak. If you were to create clients in a loop and keep a reference to all of them in an array or object with no code to ever dispose of stale clients, then yes, that would be a memory leak.

Upvotes: 3

Floby
Floby

Reputation: 2336

This is correct. Event Emitters in node.js store their listeners in a private _listeners property. your handler function uses client as a closured variable, which is not strictly necessary because all handlers are called with the event emitter as the this reference.

However, using this instead of client doesn't change the fact that client is in the closure, it just hints V8 to dereference it from the closure because it is not used.

Even if it was used from the closure, V8 has sufficient logic to handles this kind of circular references and free them from memory properly.

Upvotes: 1

Related Questions