Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are JavaScript Blob objects garbage collected?

In modern browsers, it's possible to allocate a large object as a Blob, then request access to it via a URL. This URL will serve the stored object (such as an image's data) elsewhere in the browser.

How does the browser know when this URL is no longer needed, and the corresponding Blob data is free to be garbage collected?

like image 791
Drew Noakes Avatar asked Jan 18 '14 16:01

Drew Noakes


People also ask

How does garbage collection take place in JavaScript?

Mark-and-sweep algorithm Periodically, the garbage collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

Is garbage collection automatically in JavaScript?

Garbage collection is performed automatically. We cannot force or prevent it. Objects are retained in memory while they are reachable.

Are event listeners garbage collected?

Yes. The reference is being removed behind the scenes and the garbage collection also happens behind the scenes. It is a good idea to remove event listeners when you don't need them. Apps that keep recreating event listeners without removing them is a potential source of memory leaks.

Can a garbage collected language have memory leaks?

Although garbage collection prevents many types of memory leaks, it doesn't prevent all of them. In automatic reference counting systems, such as Perl or Objective-C, memory is leaked whenever there are cyclical references, since the reference count is never decremented to zero.


1 Answers

The browser will eventually clear up this resource, however it may be some while (hours or days) before it is removed from memory/disk.

If you wish to explicitly remove the object, you may do so via revokeObjectURL.

var blob = new Blob([/*JPEG data*/], {type: "image/jpeg"}),
    url = (window.URL || window.webkitURL),
    objectUrl = url.createObjectURL(blob);

// use the object URL, eg:
var img = new Image();

img.onload = function()
{
    // release the object URL once the image has loaded
    url.revokeObjectURL(objectURL);
};

// trigger the image to load
image.src = objectURL;
like image 83
Drew Noakes Avatar answered Sep 28 '22 07:09

Drew Noakes