我有一个函数,它传递了一个带有数据uri的对象。 uri将转换为blob并使用createObjectURL
显示。如何确保正确发布?
目前,如果我在chrome / firefox中拍摄快照,看起来它没有被正确释放,因为即使在我关闭对话框之后内存仍然被分配。
这是我尝试过的:
import swal from 'sweetalert2';
function dataURItoBlob (dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
// create a view into the buffer
var ia = new Uint8Array(ab);
// set the bytes of the buffer to the correct values
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {type: mimeString});
return blob;
}
/**
* Shows an attachment in the browser
* @param {Object} result The result object
* @param {String} result.uri The data uri string
*/
export function showAttachment (result) {
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = dataURItoBlob(result.uri);
// get a url
const url = URL.createObjectURL(newBlob);
const linkContent = newBlob.type.indexOf('image') > -1
? `<img src="${url}" alt="" style="width:100%;" />` : result.id;
const html = `<a href="${url}" target="_blank"><i class="fa fa-download"></i> ${linkContent}</a>`;
swal({
title: 'File Download',
html: html,
confirmButtonText: '<i class="fa fa-check"></i> Done!'
}).then(() => {
window.URL.revokeObjectURL(url);
});
}
答案 0 :(得分:1)
大多数人在分析内存时忘记的是,在释放资源后,GC并不总是直接启动。特别是V8通常是罕见的停止世界。要真正测试它是否被收集,请调用它几千次,以便RAM填满并且GC需要启动。