function f() {
// some code.. then:
var bloburl = URL.createObjectURL(canvasToBlobOutput)
// I could would do the following line, but assume I don't
// imgElement.src = bloburl;
// will this leak memory?
}
如果我取消注释 imgElement.src 行,我知道 img 元素会“ Hook ”内存中的 blob 对象。但是,如果我们像现在这样运行该函数(没有这一行),我看不出 bloburl
无法被 GC 的原因?因为我们在函数之后没有引用它。
最佳答案
字符串不能充当 blob 的 GC 边缘,因为字符串可以被操作。因此,必须将 blob 放入内部注册表中,以防止其被 GC 处理,以便可以从生成的 blob URI 加载它。
想象有一个隐藏的 Map
实例和 URL.createObjectURL
实现为:
function createObjectURL(blob) {
let uri = generateRandomURI()
window._hiddenMap.set(uri, blob)
return uri
}
这样,当有人尝试加载该 URI 时,可以检查内部映射。但该映射还必须使 Blob 保持事件状态,因为 URI 可能是对该 Blob 唯一剩余的引用。
要删除该 gc-edge,您必须撤销 URI。
关于JavaScript 为什么 window.URL.createObjectURL 需要撤销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37813676/