|
|

192-毛毛熊_谷歌网页填表_浏览器内存溢出崩溃Out of Memory
/**
* 基础内存溢出测试 - 无限创建大对象
* 原理:将大对象存入数组,阻止GC(垃圾回收),持续占用内存直至溢出
*/
function testMemoryOverflowBasic() {
// 用于存储大对象,阻止垃圾回收
const memoryHog = [];
let count = 0;
console.log('开始内存溢出测试...');
console.log(`初始内存占用:${(performance.memory.usedJSHeapSize / 1024 / 1024).toFixed(2)} MB`);
// 定时创建大对象
const interval = setInterval(() => {
try {
// 创建一个大尺寸的对象(包含大量数据)
const bigObject = {
data: new Array(1024 * 1024).fill('test' + Math.random()), // 约4MB/个(字符串数组)
nested: new Array(512 * 512).fill({
value: Math.random()
}), // 嵌套对象增加内存占用
timestamp: Date.now()
};
memoryHog.push(bigObject);
count++;
// 每100次输出内存状态
if (count % 100 === 0) {
const usedMB = (performance.memory.usedJSHeapSize / 1024 / 1024).toFixed(2);
console.log(`已创建 ${count} 个大对象,当前内存占用:${usedMB} MB`);
}
} catch (error) {
// 捕获内存溢出错误
console.error('内存溢出触发!', error.message);
console.log(`总共创建了 ${count} 个大对象`);
clearInterval(interval);
// 可选:清空数组(验证内存释放)
// memoryHog.length = 0;
}
}, 10); // 每10ms创建一个,加速溢出
}
// 执行测试
testMemoryOverflowBasic();
|
|