ES6 Collections Map vs WeakMap

Posted By : Manisha Kirodiwal | 28-Nov-2018

JavaScript Garbage Collection is a form of memory management where objects that are no longer referenced are automatically deleted and their resources are recycled.

 

Map and Set's references to objects are kept strong and do not allow the collection of waste. This can be expensive if the map / set refers to large objects that are no longer needed, for example. DOM items already removed from DOM.

 

In order to remedy this, ES6 also introduces two new weak collections called WeakMap and WeakSet.WeakMap was also introduced by ES6 in 2015. These ES6 collections are "weak" because they allow items that no longer need to be cleared from memory.
By the name we can guess there is a certain kind of card that can be; but in fact it is not. WeakMap is not inherited from Map. But their functionalities are very similar.

 

The differences that Map has with Objects; is also true (majorly) for WeakMap. The main difference between Map and WeakMap is, WeakMap weakens the references to key objects. Thus, if the object is deleted somewhere in the program, WeakMap will also release the value mapped to the object. This prevents memory leakage. This is the reason why WeakMap is used to declare private variables. However, there are several differences between Map & WeakMap.

 

For Object:

let john = { name: "John" };
// the object is accessible, john is the reference to it
// overwrite the reference
john = null;
// the object will be removed from memory

 

Normally, properties of an object or elements in an array or other data structure are considered to be available and stored in memory while the data structure is in memory.

In an ordinary Map, it does not matter if we store an object as a key or as a value. It is stored in memory, though there are no more references to it.

let john = { name: "John" };
let map = new Map();
map.set(john, "...");
john = null; // overwrite the reference
// john is stored inside the map
// we can get it by using map.keys()

 

With the exception of WeakMap / WeakSet.

WeakMap / WeakSet does not prevent the object's removal from memory.

 

let john = { name: "John" };
let weakMap = new WeakMap();
weakMap.set(john, "...");
john = null; // overwrite the reference
// john is removed from memory!

 

Compare it with the usual Map example above. Now, if John only exists as the key to WeakMap - it will be automatically deleted.

 

 

About Author

Author Image
Manisha Kirodiwal

Manisha is a Web Application developer and she is good in working with Angular, TypeScript , JavaScript and Jquery. In free time she loves to dance and cooking.

Request for Proposal

Name is required

Comment is required

Sending message..