WeakMap feature
-
WeakMap can only use objects as key names (except null)
-
Objects referenced by key names are weak references
-
WeakMap is not traversable
Strong reference:
let a = {
name: "eric", age: 20}
let arr = [a, "other"]
当不需要时,需要手动切断引用,GC才能回收。
a = null;
arr[0] = null;
同理Map也是如此
Weak Quote:
弱引用不参与垃圾回收的机制,也就是说GC在回收时不考虑弱引用的影响
当一个对象被回收后,相关的弱引用也会自动消失
比如
let a = {
name: "eric", age: 20}
let wp = new WeakMap();
wp.set(a, new Array(10 * 1024 * 1024));
此时如果 a = null;
wp里的键名对象和所对应的键值对会自动消失,不用手动删除引用
Use cases to prove the recovery process of 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;
})
- Open
chrome
the console, findperformance monitor
the panel, and you can see the initialjs heap size
approx.45M
- Click
button
the button tokey
set it tonull
, then clickchrome
the consoleMemony
panelGC
icon (the trash can on the left), and check againjs heap size
about yes45M
(no change)
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;
})
- Open
chrome
the console, findperformance monitor
the panel, and you can see the initialjs heap size
approx.45M
- Click
button
the button tokey
set it tonull
, then clickchrome
the consoleMemony
panelGC
icon (the trash can on the left), and check againjs heap size
about3M
(obviously smaller)- It means that the memory referenced in wp has been reclaimed by GC.
- In summary, the weak reference mechanism of WeakMap is proved.