WeakMap特性
-
WeakMap只能将对象作为键名(null除外)
-
键名引用对象是弱引用
-
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;
})
- 打开
chrome
控制台,找到performance monitor
面板,可以看到初始js heap size
约是45M
- 点击
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;
})
- 打开
chrome
控制台,找到performance monitor
面板,可以看到初始js heap size
约是45M
- 点击
button
按钮将key
置为null
,然后点击chrome
控制台Memony
面板GC
图标(左侧的垃圾桶),再次查看js heap size
约是3M
(明显变小了)- 说明wp中引用的内存被GC回收了。
- 综上也就证明了WeakMap的弱引用机制。