Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object memory management when using delete on property

I'm currently writing a node.js/socket.io application but the question is general to javascript.

I have an associative array that store a 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 statement, I fear that it will make a memory leak as the property named after client.sessionId value(associative arrays are objects) won't be deleted, its reference to its value will be gonne but the property will still exist in the object.

Am I right?

like image 467
Moop Avatar asked Apr 21 '11 20:04

Moop


1 Answers

delete clientColors[client.sessionId];

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

Now if you asked whether this created a memory leak in IE4 then that's a different question. v8 on the other hand can handle this easily.

Seeing as you deleted the only reference the property will also be gone. Also note that objects are not "associative arrays" in javascript since ordering is implementation specific and not garantueed by the ES specification.

like image 175
Raynos Avatar answered Nov 14 '22 21:11

Raynos