Managing Javascript Object Memory Using Delete on Property

I am currently writing a node.js / socket.io application, but the question is common to javascript.

I have an associative array that preserves the color for each client connection. Consider the following:

var clientColors = new Array(); //This execute each new connection socket.on('connection', function(client){ clientColors[client.sessionId] = "red"; //This execute each time a client disconnect client.on('disconnect', function () { delete clientColors[client.sessionId]; }); }); 

If I use the delete operator, I fear that this will lead to a memory leak, since the property named client.sessionId (associative arrays - objects) will not be deleted, its reference to its value will be gonne, but the property will still exist in the object .

I'm right?

+6
source share
3 answers

delete clientColors[client.sessionId];

This will remove the reference to the object on the clientColors object. Garbage collector v8 will collect any objects with zero references for garbage collection.

Now, if you asked if this caused a memory leak in IE4, then another question arises. v8, on the other hand, can easily handle this.

Seeing that you have removed the only link, the property will also disappear. Also note that objects are not “associative arrays” in javascript, since ordering is implementation-specific and not specified by the ES specification.

+12
source

Since clientColors[client.sessionId] is a primitive value (string) in this case, it will be immediately deleted.

Consider the more complicated case foo[bar] = o with o as non-primitive (some object). It is important to understand that o not stored “inside” foo , but somewhere in an arbitrary memory location. foo just contains a pointer to this location. When you call delete foo[bar] , this pointer is cleared, and it frees the memory occupied by o until the garbage collector.

BTW: you should not use Array if you want an associative array. The latter is called Object in Javascript and is usually created using the short quasi-literal {}

+4
source

If you use a V8 engine or nodejs / io, this may not lead to a leak, but it is always recommended to prevent leaks.

Just delete it

 delete clientColors[client.sessionId]; 

Or set it to null

 clientColors[client.sessionId] = null; 

which will also be a cascade for any prototypically inherited objects.

Thus, there is practically no likelihood of triggering a leak.

-1
source

Source: https://habr.com/ru/post/886417/


All Articles