Case demonstration of weak reference and garbage collection of WeakMap

WeakMap feature

  1. WeakMap can only use objects as key names (except null)

  2. Objects referenced by key names are weak references

  3. 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;
})

insert image description here

  1. Open chromethe console, find performance monitorthe panel, and you can see the initial js heap sizeapprox.45M
  2. Click buttonthe button to keyset it to null, then click chromethe console Memonypanel GCicon (the trash can on the left), and check again js heap sizeabout yes 45M(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;
})

insert image description here

  1. Open chromethe console, find performance monitorthe panel, and you can see the initial js heap sizeapprox.45M
  2. Click buttonthe button to keyset it to null, then click chromethe console Memonypanel GCicon (the trash can on the left), and check again js heap sizeabout 3M(obviously smaller)
  3. It means that the memory referenced in wp has been reclaimed by GC.
  4. In summary, the weak reference mechanism of WeakMap is proved.

Guess you like

Origin blog.csdn.net/mochenangel/article/details/125503606