Memory Leak
按下 GO 按鈕後到 Performance 面板按下 Collect garbage 來強制 GC。
Create Array
打開 DevTools Drawer 內的 Performance monitor,搭配 GC 看看 JS heap size
的變化。
只建立 Array ->
function createArray(n = 1000000) {
return new Array(n).fill('Hello World!');
}
新建 Array 且用變數儲存 ->
function appendArray() {
if (Array.isArray(array)) {
array = array.concat(createArray());
} else {
array = createArray();
}
}
清掉 Array ->
function clearArray() {
array = undefined;
}
Create DOM
搭配 GC 看看 DOM Nodes 的變化。
只建立元素 ->
function createDOM() {
return createArray(100).map((text) => {
const node = document.createElement('div');
node.textContent = text;
return node;
});
}
新建元素且用變數儲存 ->
function appendDOM() {
const container = document.querySelector('.dom-container');
if (!dom) {
dom = document.createElement('div');
}
const doms = createDOM();
dom.append(...doms);
container.appendChild(dom);
}
移除元素 ->
function removeDOM() {
if (dom) dom.remove();
}
清除元素和變數 ->
function clearDOM() {
removeDOM();
dom = undefined;
}
DOM container