Skip to content

Commit 7e373d9

Browse files
修改WeakMap内存测试demo;
WeakMap中的弱引用是针对key的,而不是针对vlaue;
1 parent 24b5330 commit 7e373d9

File tree

1 file changed

+11
-24
lines changed

1 file changed

+11
-24
lines changed

docs/set-map.md

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1014,45 +1014,32 @@ undefined
10141014
> let wm = new WeakMap();
10151015
undefined
10161016

1017-
> let b = new Object();
1017+
> let key = new Array(5*1024*1024);
10181018
undefined
10191019

1020-
> global.gc();
1021-
undefined
1022-
1023-
// 此时,heapUsed 仍然为 4M 左右
1024-
> process.memoryUsage();
1025-
{ rss: 20537344,
1026-
heapTotal: 9474048,
1027-
heapUsed: 3967272,
1028-
external: 8993 }
1029-
1030-
// 在 WeakMap 中添加一个键值对,
1031-
// 键名为对象 b,键值为一个 5*1024*1024 的数组
1032-
> wm.set(b, new Array(5*1024*1024));
1020+
> wm.set(key,1);
10331021
WeakMap {}
10341022

1035-
// 手动执行一次垃圾回收
10361023
> global.gc();
10371024
undefined
10381025

1039-
// 此时,heapUsed 为 45M 左右
1026+
// 可以看到,增加数组key之后,heapUsed增加到45M了;
10401027
> process.memoryUsage();
1041-
{ rss: 62652416,
1042-
heapTotal: 51437568,
1043-
heapUsed: 45911664,
1044-
external: 8951 }
1028+
{ rss: 67538944,
1029+
heapTotal: 7376896,
1030+
heapUsed: 45782816,
1031+
external: 8945 }
10451032

1046-
// 解除对象 b 的引用
1047-
> b = null;
1033+
// 清除外界对key的引用,但没有手动清除WeakMap对key的引用
1034+
> key = null;
10481035
null
10491036

10501037
// 再次执行垃圾回收
10511038
> global.gc();
10521039
undefined
10531040

1054-
// 解除 b 的引用以后,heapUsed 变回 4M 左右
1055-
// 说明 WeakMap 中的那个长度为 5*1024*1024 的数组被销毁了
1041+
// heapUsed 4M左右,
1042+
// 可以看到WeakMap对key的引用没有阻止gc对key所占内存的回收;
10561043
> process.memoryUsage();
10571044
{ rss: 20639744,
10581045
heapTotal: 8425472,

0 commit comments

Comments
 (0)