I'm using blob to download files, Problem is I want to keep Object URL even after downloading the file, without making major changes in code base.
So one of the option is not to call URL.revokeObjectURL();
Is it safe to depend on browser's garbage collector to avoid any memory leak?
Do I always need to call URL.revokeObjectURL();
explicitly ?
The other answer is right, but I thought I should add some info for the sake of completeness.
It mainly depends on what you pass to createObjectURL
.
If you pass a File selected by the user from an <input type=file>
, then the blobURI you created is a direct pointer to the file on the user's disk, nothing apart this mapping URI-file_path is saved in memory. So in this case, you can create a lot of these without ever revoking it with no real risk.
If you pass a Blob (or a File) that you did generate (or which has been fetched), then the Blob has to be stored in memory, and the blobURI will indeed keep being a pointer to this Blob and its data, protecting it from GC, until the document dies. In this case, don't forget to revoke it when you don't need it anymore.
If you pass a MediaStream coming from the user device, don't, it's being deprecated and for good reasons: As for the generated Blob, UAs had to keep the connection to the external device open while the blobURI is alive, and even though the MediaStream was closed, it could happen the connection was still open and lead to unavailability of requesting new connections.
Is it safe to depend on browser's garbage collector to avoid any memory leak?
What createObjectURL
approximately¹ does is to create a mapping of the ID in the created blob URL to the actual blob in a hidden Map
associated with the current global object. Which means from the perspective of the GC the Blob remains reachable until either the global itself becomes collectible - commonly when you navigate away from the page or close a tab - or when the mapping is revoked (assuming that was the last reference).
So it depends on what you consider as a leak. It won't remain alive for the lifetime of the browser, only for the lifetime of the current page. You need to revoke if you want its lifetime to be potentially shorter than the current page.
¹ That's not exactly how it's implemented, but it describes the behavior reasonably well when reasoning about reachability.
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