-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_data_structure_weakset.js
72 lines (61 loc) · 2.16 KB
/
js_data_structure_weakset.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
function SetExample() {
const mySet = new Set();
let obj = { a: 1 };
mySet.add(obj);
console.log(mySet);
obj = null;
console.log(mySet);
}
function WeakSetExample01() {
const weakSet = new WeakSet();
let obj = { message: 'Hello' };
weakSet.add(obj);
console.log(weakSet.has(obj));
obj = null;
console.log(weakSet.has(obj));
}
function WeakSetExample02() {
const myWeakSet = new WeakSet();
const obj = { name: 'Alice' };
myWeakSet.add(obj);
console.log(myWeakSet.has(obj));
myWeakSet.delete(obj);
console.log(myWeakSet.has(obj));
}
function WeakSetExample03() {
const myWeakSet = new WeakSet();
const obj = { title: 'TDK' };
myWeakSet.add(obj);
// no result
console.log(myWeakSet.size);
/* myWeakSet.forEach((value) => {
console.log(value);
}); */
}
SetExample();
WeakSetExample01();
WeakSetExample02();
WeakSetExample03();
/*
Q: what is garbage-collection?
A: when a value becomes non-reachable / non-referenced, memory will be de-allocated and value will be garbage-collected
usecase 01 / non-reachable :
every pointer is unique
so, if pointer got replaced without backup, we lose it forever
and value will be non-reachable
usecase 02 / non-referenced :
pointer exists from the declaration-statement to last-utilization-statement
after that value will be non-referenced
action : so, Javascript engine will identify and remove that value from memory (memory deallocation)
and value will be a garbage (garbage-collection)
Q: weakmap supports only reference-object to prevent memory leak, how so?
A: setting a value against a reference-object, means : encrypt value using a dedicated unique password
only way to retrieve the value, using that password
if we lose the password, value and password, both will be garbage-collected
so, no memory leak !
Q: weakset supports only reference-object to prevent memory leak, how so?
A: storing a reference-object in a weakset, means : putting a pointer in a locker
only way to know if the pointer does exist in the locker, is to pass the exact pointer
if we lose the pointer, value of the pointer will be garbage-collected
so, no memory leak !
*/