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?
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.
Garbage collection is performed automatically. We cannot force or prevent it. Objects are retained in memory while they are reachable.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With