Delete Javascript Blobs?
Solution 1:
This looks like you have a memory leak.
JavaScript doesn't have a "delete" in the sense you're talking about, it garbage collects as properties and variables become orphaned. The delete
operator is one such way to achieve that - it removes the definition of a property from an Object.
Using delete
correctly means using it on a property, not a var
iable. The reason it works on some variables is because of what happens with var
in the global namespace (i.e. they become properties of window
). This also means you can't delete
a parameter.
Further, note that once a function has finished invoking, if there are no references being kept alive then all of it's internals will be GC'd.
Next, consider
var o = {};
o.a = [];
o.b = o.a;
delete o.a;
What is o.b
now?
`o.b; // []`
It's still pointing at the Array even though we deleted the o.a
reference. This means that the Arraywon't be garbage collected.
So what does this mean for you?
To get rid of your Blobs, you need to destroy all the references to them.
Yes, revoking the URI is part of it, but you also need to remove references all the way through your code. If you're finding this difficult, I'd suggest you wrap all your Blobs so you can at least minimise the problem.
var myBlob = (function () {
var key, o;
functionmyBlob(blob) {
var url;
this.blob = blob;
blob = null;
this.getURL = function () {
if (url) return url;
return url = URL.createObjectURL(this.blob);
};
this.dispose = function () {
if (url) url = URL.revokeObjectURL(url), undefined;
this.blob = null;
};
}
o = newBlob();
for (key in o)
(function (key) {
Object.defineProperty(myBlob.prototype, key, {
enumerable: true,
configurable: true,
get: function () {returnthis.blob[key];}
});
}(key));
o = key = undefined;
return myBlob;
}());
Now, instead of your regular Blob creation use new myBlob(blob)
immediately as you make your blob, keeping no other references to the blob. Then when you're finished with your Blob, call myWrappedBlob.dispose();
and it should free it up to be GC'd. If it's really necessary to pass the Blob into something directly, I gave it the property myBlob.blob
.
Post a Comment for "Delete Javascript Blobs?"