案例演示WeakMap的弱引用与垃圾回收

WeakMap特性

  1. WeakMap只能将对象作为键名(null除外)

  2. 键名引用对象是弱引用

  3. WeakMap不可遍历

强引用:

let a = {
    
    name: "eric", age: 20}
let arr = [a, "other"]
当不需要时,需要手动切断引用,GC才能回收。
a = null;
arr[0] = null;
同理Map也是如此

弱引用:

弱引用不参与垃圾回收的机制,也就是说GC在回收时不考虑弱引用的影响
当一个对象被回收后,相关的弱引用也会自动消失
比如
let a = {
    
    name: "eric", age: 20}
let wp = new WeakMap();
wp.set(a, new Array(10 * 1024 * 1024));
此时如果 a = null;
wp里的键名对象和所对应的键值对会自动消失,不用手动删除引用

用案例来证明GC的回收过程

1. Map

<button>null</button>
const buttonNode = document.querySelector("button");
let key = {
    
    
	name: "Eric",
	age: 20
}
let map = new Map();
map.set(key, new Array(10 * 1024 * 1024));

buttonNode.addEventListener("click", () => {
    
    
	key = null;
})

在这里插入图片描述

  1. 打开chrome控制台,找到performance monitor面板,可以看到初始js heap size 约是 45M
  2. 点击button按钮将key置为null,然后点击chrome控制台Memony面板GC图标(左侧的垃圾桶),再次查看js heap size 约是 45M(没有变化)

2.WeakMap

<button>null</button>
const buttonNode = document.querySelector("button");
let key = {
    
    
  name: "Eric",
  age: 20
}
let wp = new WeakMap();
wp.set(key, new Array(10 * 1024 * 1024));

buttonNode.addEventListener("click", () => {
    
    
	key = null;
})

在这里插入图片描述

  1. 打开chrome控制台,找到performance monitor面板,可以看到初始js heap size 约是 45M
  2. 点击button按钮将key置为null,然后点击chrome控制台Memony面板GC图标(左侧的垃圾桶),再次查看js heap size 约是 3M(明显变小了)
  3. 说明wp中引用的内存被GC回收了。
  4. 综上也就证明了WeakMap的弱引用机制。

猜你喜欢

转载自blog.csdn.net/mochenangel/article/details/125503606