我想知道是否可以通過永不會恢復的異步函數創建內存泄漏。例如:使用異步方法瞭解Chrome GC
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function Test() {
this.arr = [];
this.alloc = async function() {
for (i = 0; i < 300000; i++) {
this.arr.push(document.createElement('div'));
}
await timeout(10000);
alert('done waiting ' + this.arr.length); // outputs 300000
};
};
var test = new Test();
function leak() {
test.alloc();
test = null;
window.gc(); // Running chrome with expose-gc flag
// Snapshotting memory here shows divs have been deallocated
}
使用Chrome的內存工具,當這段代碼完成執行時,我抓住了一個快照。我預計會看到300000個HTMLDivElements仍然被分配,但是你會發現 - 內存似乎「被釋放」了。奇怪的是,如果我嘗試訪問它們仍然存在的數組內容。 任何人都可以解釋這種現象嗎?
「expose-gc」標記記錄在哪裏? – guest271314
如果gc行爲怪異並且受到'console.log'(或'alert')語句的影響或者不存在,我的猜測是'await'可以啓用相同的[範圍優化,閉包得到](https:/ /stackoverflow.com/questions/28388530/why-does-chrome-debugger-think-closed-local-variable-is-undefined)。 – Bergi