原创不易,未经作者允许禁止转载!!
let arr = [1, 0, 1] // [1, 0, 1]这块内存被arr引用 引用次数为1
arr = [0, 1, 0] // [1, 0, 1]的内存引用次数为0被释放
// [0, 1, 0]的内存被arr引用 引用次数为1
const tmp = arr // [0, 1, 0]的内存被tmp引用 引用次数为2
Netscape Navigator 3.0 采用
function Example(){
let ObjectA = new Object();
let ObjectB = new Object();
ObjectA.p = ObjectB;
ObjectB.p = ObjectA;
}
Example();
ObjectA = null;
ObjectB = null;
为了解决循环引用造成的内存泄漏问题,Netscape Navigator 4.0 开始采用标记清除法 到了 2008 年,IE、Firefox、Opera、Chrome 和 Safari 都在自己的 JavaScript 实现中采用标记清理(或 其变体),只是在运行垃圾回收的频率上有所差异。
function Example(n){
const a = 1, b = 2, c = 3;
return n * a * b * c;
}
// 标记Example进入执行上下文
const n = 1; // 标记n进入执行上下文
Example(n); // 标记a,b,c进入执行上下文
console.log(n); // 标记a, b, c离开执行上下文,等待垃圾回收
V8引擎的垃圾回收采用标记清除法与分代回收法 分为新生代和老生代
新生代垃圾回收采用
Scavenge
算法 分配给常用内存和新分配的小量内存
Scavenge
算法老生代采用
mark-sweep
标记清除和mark-compact
标记整理 通常存放较大的内存块和从新生代分配过来的内存块
1类
2类
3类
1类
,然后进行深度优先遍历。2类
。3类
。1类
的对象进行内存释放img
// exm1
function Example(){
exm = 'LeBron'
}
// exm2
function Example(){
this.exm = 'LeBron'
}
Example()
const timer = setInterval(() => {
//...
}, 1000)
// clearInterval(timer)
function debounce(fn, time) {
let timeout = null;
return function () {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, time);
};
}
const fn = debounce(handler, 1000); // fn引用了timeout
const element = {
// 此处引用了DOM元素
button:document.getElementById('LeBron'),
select:document.getElementById('select')
}
document.body.removeChild(document.getElementById('LeBron'))
这个其实不难,浏览器原带的开发者工具Performance就可以
img
// exm
const fn = (idx) => {
return idx * 2;
}
function Example(){
for(let i=0;i<1000;i++){
//const fn = (idx) => {
// return idx * 2;
// }
const res = fn(i);
}
}
function Example() {
const obj = {};
let res = "";
for (let i = 0; i < 1000; i++) {
// const obj = {
// a: i,
// b: i * 2,
// c: i * 3,
// };
obj.a = i;
obj.b = i * 2;
obj.c = i * 3;
res += JSON.stringify(obj);
}
return res
}
arr = [0, 1, 2]
arr.length = 0; // 清空了数组,数组类型不变
// arr = [] // 重新申请了一块空数组对象内存