Do I always need to call URL.revokeObjectURL() explicitly?

女生的网名这么多〃 提交于 2020-05-10 20:52:52

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/49209756/do-i-always-need-to-call-url-revokeobjecturl-explicitly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!