WeakSet objects are weak references, that is, garbage collection mechanism does not consider WeakSet’s reference to the object, that is, if other objects no longer reference the object, then garbage collection mechanism will automatically recover the memory occupied by the object, not considering the object still exists in WeakSet. This is because the garbage collection mechanism determines the collection based on the reachability of the objects. If the objects are still accessible, the garbage collection mechanism will not free the memory. After you finish using the value, you sometimes forget to dereference it, causing memory to be unable to be freed, which can lead to a memory leak. WeakSet references are not included in the garbage collection mechanism, so there is no problem. Therefore, WeakSet is suitable for temporarily storing a group of objects and information bound to the object. As soon as the object disappears externally, its reference in WeakSet disappears automatically. Due to the above feature, a WeakSet member is not suitable for reference because it will disappear at any time. In addition, because the number of internal WeakSet members depends on whether garbage collection mechanism is running, the number of members may be different before and after operation, and when garbage collection mechanism is running is unpredictable, so ES6 stipulates that WeakSet cannot be traversed. These characteristics also apply to the WeakMap structure described later in this chapter. – nguyen half-stretching

Set

It’s like an array, but without a key, or the key is the same as a value. You can add, delete, empty, and determine whether a value is included. You can enumerate.

Set key=null removes a strong reference to obj from key. Set key=null removes a strong reference to OBj from set. Delete (key) unless the key is deleted from the set before setting key=null; Key = null.

const s = new Set();
let key = new Array(5 * 1024 * 1024);
s.add(key);
Copy the code

The directory structure is as follows:

The print provided by lib.js does two things — performs garbage collection and prints memory usage information, but the other files are similar.

Use node — expose-GC map.js for manual memory reclamation

// lib.js
 const format = function (bytes) {
    return (bytes / 1024 / 1024).toFixed(2) + ' MB';
};

const print = function() {
    global.gc();
    const memoryUsage = process.memoryUsage();
    console.log(JSON.stringify({
        rss: format(memoryUsage.rss),
        heapTotal: format(memoryUsage.heapTotal),
        heapUsed: format(memoryUsage.heapUsed),
        external: format(memoryUsage.external),
    }));
}

module.exports = {
    format,
    print,
}


// set.js
const lib = require('./lib');
const { print } = lib;

print();
const s = new Set();
let key = new Array(5 * 1024 * 1024);
s.add(key);
print();
key = null;
print();

// set2.js
const lib = require('./lib');
const { print } = lib;

print();
const s = new Set();
let key = new Array(5 * 1024 * 1024);
s.add(key);
print();
s.delete(key);
key = null;
print();
Copy the code

WeakSet

References to objects in a Set are strongly primed and do not allow garbage collection; It can store any type — value type or reference type.

WeakSet object reference is weak reference, that is to say, even if WeakSet “reference” an object, but garbage collection does not count this reference as “reference”, as long as there is no strong reference to this object elsewhere, the object is unreachable, may be recycled at any time; Only reference types can be stored and cannot be enumerated or cleared.

// weakset.js
const lib = require('./lib');
const { print } = lib;

print();
const s = new WeakSet();
let key = new Array(5 * 1024 * 1024);
s.add(key);
print();
key = null;
print();
Copy the code

Key = null; obj = null; obj = null; Set. Delete (key) cancels set’s strong reference to obj. Key =null cancels key’s strong reference to obj. Weakset in weakset.js is a weak reference to the object OBj referenced by key. When key=null, there is no object reference obj, obJ is unreachable, and print is recycled last time.

Map

A Map is a collection of key-value pairs that can be saved, retrieved, cleared, and deleted, and can be enumerated. The map has a strong reference to the object referenced by the key.

WeakMap

A WeakMap is similar to a Map, except that it is not enumerable, cannot be emptied, and is a weak reference to the object referenced by a key (see the WeakSet section).

Usage scenario: Register a Listener object that listens to events

const listener = new WeakMap();
 
listener.set(ele1, handler1);
listener.set(ele2, handler2);

ele1.addEventListener('click', listener.get(ele1), false);
ele2.addEventListener('click', listener.get(ele2), false);
Copy the code

Since the monitoring function is placed in WeakMap, once the DOM object ELE1 and ELE2 disappear, the monitoring functions handler1 and Handler2 bound to it will also disappear automatically, eliminating the manual removal of the monitoring function

The usage comparison of Set, Map, WeakSet and WeakMap is attached