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 th开发者_开发问答e 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?
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.
Since clientColors[client.sessionId]
is a primitive value (a string) in this case, it will be cleared immediately.
Let's consider the more complicated case of foo[bar] = o
with o
being a non-primitive (some object). It's important to understand that o
is not stored "inside" foo
, but somewhere in an arbitrary memory location. foo
merely holds a pointer to that location. When you call delete foo[bar]
, that pointer is cleared, and it's up to the garbage collector to free the memory taken by o
.
BTW: You shouldn't use Array
when you want an associative array. The latter is called Object
in Javascript and is usually instantiated using the short-hand quasi-literal {}
If you are using the V8 engine or nodejs/io, it may not lead to a leak but it is always advisable to prevent leaks.
Just delete it
delete clientColors[client.sessionId];
Or set it to null
clientColors[client.sessionId] = null;
Which will also cascade to any prototypically inherited objects.
This way there is almost no probability of starting a leak.
精彩评论