`free` operator

Isaac Schlueter i at izs.me
Thu Oct 25 16:16:53 PDT 2012

It'd be really nice if JS had a way to explicitly delete an object.

Occasionally, in complex programs, you can find yourself with a
situation where a certain type of object is leaking.  However, even if
you track down what the object is, and find the exact point in your
program where you ought to have no references to it, it's not always
obvious to know what might be holding a reference still.  It's
tempting to do this, and newcomers often think that this helps, but of
course, it does nothing:

function doStuff() {
  // some object that we're doing stuff with...

  // now we know we're done, and there should be no refs.
  // but, there are, and they're leaking.
  // I know!  I'll do this:
  delete someObject
  // surprise! that does nothing.

What do you folks think about a "free" operator (or something like it)
that would actually do what `delete` looks like it does?

var obj = {}
var foo = { ref: obj }
var obj2 = obj
free obj  // obviously this syntax probably won't work, since 'free'
is not a reserved word already
assert(obj === undefined)
assert(foo.ref === undefined)
assert(obj2 === undefined)

So, any references to the freed object would be set to undefined, and
presumably at some point, the GC will harvest it.

Yes, yes, I know, the proper way to fix a memory leak in JS is to
properly manage references, but sometimes that means rewriting this
complicated app, and it's leaking memory now, in production.

Has this been discussed before?

More information about the es-discuss mailing list