/* 隨機生成很長的字串來佔用記憶體 */ functionrandomString(length) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }
/* demoData 將持續占用記憶體空間 */ var demoData = []; functiongetData() { for (let i = 0; i < 1000; i++) { demoData.push(randomString(5000)); } } getData(); console.log(demoData);
在 Memory 中查看占用狀況
即使是清掉 console.log 也依舊有很高的佔比。 將上面的函式修改成以下後再執行一次
1 2 3 4 5 6 7 8
functiongetData() { var demoData = []; for (var i = 0; i < 1000; i++) { demoData.push(randomString(5000)) } // console.log(demoData); } getData()